import { NSQLITE_TURBOCI_ADMIN_USERS, NSQLiteTables } from "@/src/db/types";
import { _n } from "@/src/exports/client-exports";
import grabDeploymentUserDirNames from "@/src/utils/grab-deployment-user-dir-names";
import NSQLite from "@moduletrace/nsqlite";
import { execSync } from "child_process";
import { existsSync } from "fs";

type Params = {
    user_id: string | number;
};

export default async function setupDeploymentUser({ user_id }: Params) {
    const target_user_res = await NSQLite.select<
        NSQLITE_TURBOCI_ADMIN_USERS,
        (typeof NSQLiteTables)[number]
    >({
        table: "users",
        targetId: _n(user_id),
    });

    const target_user = target_user_res.singleRes;

    if (
        !target_user?.id ||
        !target_user.username ||
        target_user.is_super_admin
    ) {
        return;
    }

    const { username } = target_user;

    const {
        force_command_file,
        ssh_dir,
        ssh_key_file,
        sshd_config_file,
        user_dir,
    } = grabDeploymentUserDirNames({ user: target_user });

    let cmd = `/bin/bash << 'TURBOCIHEREDOC'\n`;

    if (!existsSync(user_dir)) {
        cmd += `useradd --create-home --shell /bin/bash --comment "TurboCI Deployment user ${username}" ${username}\n`;
        cmd += `passwd --lock "${username}"\n`;
        cmd += `mkdir -p "${ssh_dir}"\n`;
        cmd += `ssh-keygen -t ed25519 -f "${ssh_key_file}" -N "" -C "${username}@$(hostname)"\n`;
        cmd += `cp "${ssh_key_file}.pub" "${ssh_dir}/authorized_keys"\n`;

        cmd += `chown -R "${username}:${username}" "${ssh_dir}"\n`;
        cmd += `chmod 700 "${ssh_dir}"\n`;
        cmd += `chmod 600 "${ssh_key_file}"\n`;
        cmd += `chmod 644 "${ssh_key_file}.pub"\n`;
        cmd += `chmod 600 "${ssh_dir}/authorized_keys"\n`;
    }

    cmd += `cat << 'EOF' > ${force_command_file}\n`;
    cmd += `#!/bin/bash\n`;
    cmd += `case "$SSH_ORIGINAL_COMMAND" in\n`;
    cmd += `    "shell")\n`;
    cmd += `        exec /bin/bash\n`;
    cmd += `        ;;\n`;
    cmd += `    *)\n`;
    cmd += `        echo "Access denied."\n`;
    cmd += `        exit 1\n`;
    cmd += `        ;;\n`;
    cmd += `esac\n`;
    cmd += `EOF\n\n`;

    cmd += `chmod +x ${force_command_file}\n\n`;

    cmd += `cat << 'EOF' > ${sshd_config_file}\n`;
    cmd += `Match User ${username}\n`;
    cmd += `    PasswordAuthentication no\n`;
    cmd += `    PubkeyAuthentication yes\n`;
    cmd += `    AuthenticationMethods publickey\n`;
    cmd += `    AllowTcpForwarding yes\n`;
    cmd += `    X11Forwarding no\n`;
    cmd += `    ForceCommand ${force_command_file}\n`;
    cmd += `    PermitOpen localhost:80\n`;
    cmd += `    PermitTTY no\n`;
    cmd += `EOF\n`;
    cmd += `TURBOCIHEREDOC\n`;

    execSync(cmd);

    return;
}
