// src/server/utils/permissions.ts
import { execSync } from "child_process";
import { resolve } from "path";
import { access, stat } from "fs/promises";
import { constants } from "fs";
function sanitizeShellArg(arg) {
  if (!/^[a-zA-Z0-9._-]+$/.test(arg)) {
    throw new Error(`Invalid argument: ${arg}`);
  }
  return arg;
}
async function getDirInfo(targetPath) {
  const resolvedPath = resolve(targetPath);
  try {
    await access(resolvedPath, constants.F_OK);
  } catch {
    throw new Error("Path not found");
  }
  let sudoAvailable;
  try {
    execSync("sudo -n true", { stdio: "pipe" });
    sudoAvailable = true;
  } catch {
    sudoAvailable = false;
  }
  const dirStat = await stat(resolvedPath);
  const groupGid = dirStat.gid;
  const currentUser = sanitizeShellArg(execSync("id -un", { encoding: "utf-8" }).trim());
  const groupsOutput = execSync(`id -Gn ${currentUser}`, { encoding: "utf-8" }).trim();
  const userGroups = groupsOutput.split(/\s+/);
  let groupName = null;
  try {
    const rawGroupName = execSync(`getent group ${groupGid}`, { encoding: "utf-8" }).split(":")[0]?.trim();
    groupName = rawGroupName ? sanitizeShellArg(rawGroupName) : null;
  } catch {
  }
  const userInGroup = groupName ? userGroups.includes(groupName) : false;
  const groupHasWrite = (dirStat.mode & 16) !== 0;
  return { resolvedPath, groupGid, groupName, userGroups, userInGroup, groupHasWrite, sudoAvailable };
}
async function checkPermissions(targetPath) {
  try {
    const info = await getDirInfo(targetPath);
    return {
      success: true,
      sudoAvailable: info.sudoAvailable,
      userInGroup: info.userInGroup,
      groupHasWrite: info.groupHasWrite,
      groupName: info.groupName
    };
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    if (message === "Path not found") {
      return { success: false, error: message, status: 404 };
    }
    return { success: false, error: err instanceof Error ? err.message : "Unknown error", status: 500 };
  }
}
async function fixPermissions(targetPath, action) {
  try {
    const info = await getDirInfo(targetPath);
    if (action === "group") {
      if (!info.userInGroup) {
        return {
          success: false,
          sudoAvailable: info.sudoAvailable,
          error: 'You are not in the group that owns this directory. Use "Join group & extend group permissions" instead.'
        };
      }
      execSync(`sudo chmod g+w "${info.resolvedPath}"`, { stdio: "pipe" });
      return { success: true, sudoAvailable: info.sudoAvailable, method: "group" };
    }
    if (action === "join_group") {
      if (!info.groupName) {
        return { success: false, sudoAvailable: info.sudoAvailable, error: "Could not determine group name" };
      }
      const currentUser = execSync("id -un", { encoding: "utf-8" }).trim();
      execSync(`sudo usermod -aG ${sanitizeShellArg(info.groupName)} ${sanitizeShellArg(currentUser)}`, {
        stdio: "pipe"
      });
      return { success: true, sudoAvailable: info.sudoAvailable, method: "join_group" };
    }
    if (action === "join_group_and_group") {
      if (!info.groupName) {
        return { success: false, sudoAvailable: info.sudoAvailable, error: "Could not determine group name" };
      }
      execSync(`sudo chmod g+w "${info.resolvedPath}"`, { stdio: "pipe" });
      const currentUser = execSync("id -un", { encoding: "utf-8" }).trim();
      execSync(`sudo usermod -aG ${sanitizeShellArg(info.groupName)} ${sanitizeShellArg(currentUser)}`, {
        stdio: "pipe"
      });
      return { success: true, sudoAvailable: info.sudoAvailable, method: "join_group_and_group" };
    }
    const ownerUser = execSync("id -un", { encoding: "utf-8" }).trim();
    execSync(`sudo chown -R ${sanitizeShellArg(ownerUser)} "${info.resolvedPath}"`, { stdio: "pipe" });
    return { success: true, sudoAvailable: info.sudoAvailable, method: "ownership" };
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    if (message === "Path not found") {
      return { success: false, sudoAvailable: true, error: message, status: 404 };
    }
    return { success: false, sudoAvailable: true, error: message };
  }
}
export {
  checkPermissions,
  fixPermissions
};
//# sourceMappingURL=permissions-Z2IIV2V7.js.map