import { execSync } from "child_process";
import { writeRunScript } from "./writeRunScript.js";
function readCrontab() {
    try {
        return execSync("crontab -l", {
            stdio: ["pipe", "pipe", "pipe"],
        }).toString();
    }
    catch {
        return "";
    }
}
function writeCrontab(content) {
    execSync("crontab -", { input: content });
}
function filterLines(crontab, name) {
    const marker = new RegExp(`# agency:${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`);
    return crontab.split("\n").filter((line) => !marker.test(line));
}
export class CrontabBackend {
    install(entry) {
        const runScriptPath = writeRunScript(entry);
        const lines = filterLines(readCrontab(), entry.name);
        // The "# agency:<name>" suffix is a marker used by filterLines to identify
        // and remove our entries without affecting the user's other crontab lines.
        lines.push(`${entry.cron} /bin/bash "${runScriptPath}" # agency:${entry.name}`);
        const content = lines.filter((l) => l.trim() !== "").join("\n") + "\n";
        writeCrontab(content);
    }
    uninstall(name) {
        const existing = readCrontab();
        if (!existing)
            return;
        const lines = filterLines(existing, name);
        const content = lines.filter((l) => l.trim() !== "").join("\n") + "\n";
        writeCrontab(content);
    }
}
