import { v4 as uuidv4 } from "uuid";
import fs from "node:fs";
import path from "node:path";
import { exec } from "node:child_process";

export async function disownExecutor(command: string) {
  exec(`nohup ${command} > /dev/null 2>&1 &`);
}

export async function uuidLockEcecutor(command: string) {
  const commandId = uuidv4();
  const lockfilePath = path.resolve(`./locks/${commandId}.lock`);

  const newCommand = `
  date > ${lockfilePath} ;
  ${command} ;
  rm ${lockfilePath} ;
  `;

  exec(newCommand);

  // wait for the lockfile to be removed

  // sleep for 1 second before checking if the lockfile is removed
  await new Promise((resolve) => setTimeout(resolve, 1000));

  while (fs.existsSync(lockfilePath)) {
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
}
