#!/bin/zsh
set -euo pipefail
# Compatibility recovery for existing installs. Built-in macOS only; no Python.
[[ "$(/usr/bin/uname -s)" == Darwin ]] || { print -u2 'Screenshot Clock is for macOS only.'; exit 1; }
dry_run=false
user_root="$HOME"
if [[ "${1:-}" == --dry-run ]]; then
  dry_run=true
  [[ -z "${2:-}" ]] || user_root="$2"
elif (( $# )); then
  print -u2 'Use --dry-run [fixture home] to inspect the restoration plan.'
  exit 2
fi
/usr/bin/osascript -l JavaScript - "$user_root" "$dry_run" <<'JXA'
ObjC.import('Foundation');
function run(args) {
  var home = args[0], dry = args[1] === 'true';
  var fm = $.NSFileManager.defaultManager;
  var support = home + '/Library/Application Support/Kelowna Film Studios/macosscreenshot';
  var label = 'com.kelownafilmstudios.macosscreenshot';
  var agent = home + '/Library/LaunchAgents/' + label + '.plist';
  var snapshots = [support + '/restore-settings.json', home + '/.macos_screenshot_settings.txt'];
  function exists(p) { return fm.fileExistsAtPath($(p)); }
  var installed = [support + '/config.json', support + '/macosscreenshot.py', agent].concat(snapshots).some(exists);
  if (!installed) return 'Screenshot Clock is not installed. No screenshot settings were changed.';
  var source = snapshots.filter(exists)[0];
  var saved = null;
  if (source) {
    var content = $.NSString.stringWithContentsOfFileEncodingError($(source), $.NSUTF8StringEncoding, null);
    if (!content) throw Error('Cannot read saved settings. Nothing was changed; the restore file was kept.');
    saved = JSON.parse(ObjC.unwrap(content));
    if (!saved.managed_defaults) throw Error('Incomplete restore file. Nothing was changed; the restore file was kept.');
  }
  var managed = {'com.apple.screencapture':['name','location','show-thumbnail'], 'NSGlobalDomain':['AppleICUForce24HourTime']};
  var plan = [];
  Object.keys(managed).forEach(function(domain) {
    managed[domain].forEach(function(key) {
      var entry = saved && saved.managed_defaults[domain] && saved.managed_defaults[domain][key];
      if (saved && !entry && key === 'show-thumbnail') return;
      if (saved && (!entry || typeof entry.exists !== 'boolean')) throw Error('Incomplete restore file. Nothing was changed.');
      var value = entry && entry.exists ? entry.value : null;
      var isBool = key === 'show-thumbnail' || key === 'AppleICUForce24HourTime';
      if (entry && entry.exists && (value === null || value === undefined)) throw Error('Missing saved value. Nothing was changed.');
      if (value !== null) {
        if (isBool && !/^(0|1|true|false|yes|no)$/i.test(String(value))) throw Error('Invalid saved boolean. Nothing was changed.');
        if (!isBool && typeof value !== 'string') throw Error('Invalid saved setting. Nothing was changed.');
      }
      plan.push({domain:domain,key:key,value:value,isBool:isBool});
    });
  });
  if (dry) return JSON.stringify({installed:true,source:source || null,plan:plan});
  var app = Application.currentApplication(); app.includeStandardAdditions = true;
  function quote(s) { return "'" + String(s).replace(/'/g, "'\\''") + "'"; }
  function exec(parts) { return app.doShellScript(parts.map(quote).join(' ')); }
  var uid = exec(['/usr/bin/id','-u']);
  try { exec(['/bin/launchctl','bootout','gui/' + uid + '/' + label]); } catch (_) {}
  plan.forEach(function(p) {
    if (p.value === null) {
      try { exec(['/usr/bin/defaults','delete',p.domain,p.key]); } catch (_) {}
    } else {
      var value = p.isBool ? (/^(1|true|yes)$/i.test(String(p.value)) ? 'true' : 'false') : p.value;
      exec(['/usr/bin/defaults','write',p.domain,p.key,p.isBool ? '-bool' : '-string',value]);
    }
  });
  [agent,home + '/.local/bin/macosscreenshot',home + '/.local/bin/macosscreenshot-uninstall',snapshots[1],support].forEach(function(p) {
    if (exists(p) && !fm.removeItemAtPathError($(p), null)) throw Error('Settings restored, but could not remove ' + p + '.');
  });
  try { exec(['/usr/bin/killall','SystemUIServer']); } catch (_) {}
  return 'Screenshot Clock uninstalled. Your screenshot files and folders were kept.';
}
JXA
