import { exec } from 'child_process';
import util from 'util';

const execAsync = util.promisify(exec);

// Stasis Field: macOS Update Control
// Requires sudo for most operations.

export async function disableAutoUpdates(password?: string) {
    // Command to disable auto-update
    // defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled -bool false
    // softwareupdate --schedule off

    const cmds = [
        'sudo -S softwareupdate --schedule off',
        'sudo -S defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled -bool false',
        'sudo -S defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload -bool false',
        'sudo -S defaults write /Library/Preferences/com.apple.commerce AutoUpdate -bool false'
    ];

    // Note: Handling password securely is tricky via IPC. 
    // Usually we prompt via a sudo-capable executor (like osascript with administrator privileges).

    try {
        await execWithSudo('softwareupdate --schedule off');
        // More commands...
        return true;
    } catch (error) {
        console.error('Failed to disable updates', error);
        return false;
    }
}

async function execWithSudo(command: string) {
    const script = `do shell script "${command}" with administrator privileges`;
    return execAsync(`osascript -e '${script}'`);
}

export async function ignoreUpdate(label: string) {
    // softwareupdate --ignore <label>
    // Note: --ignore flag is deprecated/removed in recent macOS for major updates, but might work for minor.
    return execWithSudo(`softwareupdate --ignore "${label}"`);
}
