#!/bin/zsh
# virtual-hid-setup — prepare and gate Karabiner VirtualHID setup for HelperAI.
#
# Usage:
#   virtual-hid-setup status
#   virtual-hid-setup prepare [--cache-dir DIR]
#   virtual-hid-setup install --i-understand-sudo [--cache-dir DIR]
#   virtual-hid-setup activate --i-understand-sudo
#
# Safety:
#   prepare downloads and verifies the pqrs package only.
#   install and activate require an explicit flag because they use sudo.
#   This tool never reboots. Reboot still needs explicit current-turn approval.
set -euo pipefail

usage() {
  awk 'NR == 1 { next } /^set -/ { exit } { sub(/^# ?/, ""); print }' "${(%):-%x}"
}

BIN_DIR="${0:A:h}"
ROOT_DIR="${BIN_DIR:h}"
DOCTOR="$BIN_DIR/virtual-hid-doctor"
DEFAULT_CACHE_DIR="$HOME/Library/Caches/HelperAI/virtual-hid"
RELEASE_API="https://api.github.com/repos/pqrs-org/Karabiner-DriverKit-VirtualHIDDevice/releases/latest"
MANAGER="/Applications/.Karabiner-VirtualHIDDevice-Manager.app/Contents/MacOS/Karabiner-VirtualHIDDevice-Manager"

ACTION="${1:-status}"
case "$ACTION" in
  -h|--help|help)
    usage
    exit 0
    ;;
  status|prepare|install|activate)
    shift || true
    ;;
  *)
    echo "virtual-hid-setup: unknown action: $ACTION" >&2
    usage >&2
    exit 64
    ;;
esac

CACHE_DIR="$DEFAULT_CACHE_DIR"
ALLOW_SUDO=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --cache-dir)
      CACHE_DIR="$2"
      shift 2
      ;;
    --i-understand-sudo)
      ALLOW_SUDO=1
      shift
      ;;
    *)
      echo "virtual-hid-setup: unknown argument: $1" >&2
      exit 64
      ;;
  esac
done

sudo_cmd() {
  if [[ "$(id -u)" -eq 0 ]]; then
    "$@"
  else
    /usr/bin/sudo "$@"
  fi
}

latest_release_info() {
  /usr/bin/curl -fsSL --retry 3 "$RELEASE_API" |
    /usr/bin/python3 -c '
import json
import sys

data = json.load(sys.stdin)
assets = data.get("assets") or []
matches = [
    asset for asset in assets
    if asset.get("name", "").endswith(".pkg")
    and "VirtualHIDDevice" in asset.get("name", "")
    and asset.get("browser_download_url")
]
if not matches:
    raise SystemExit("no VirtualHIDDevice .pkg asset found in latest release")
asset = matches[0]
print(data.get("tag_name", ""))
print(asset["name"])
print(asset["browser_download_url"])
'
}

download_pkg() {
  /bin/mkdir -p "$CACHE_DIR"
  local info tag asset_name asset_url pkg_path
  info="$(latest_release_info)"
  tag="$(printf '%s\n' "$info" | /usr/bin/sed -n '1p')"
  asset_name="$(printf '%s\n' "$info" | /usr/bin/sed -n '2p')"
  asset_url="$(printf '%s\n' "$info" | /usr/bin/sed -n '3p')"
  if [[ -z "$tag" || -z "$asset_name" || -z "$asset_url" ]]; then
    echo "virtual-hid-setup: failed to resolve latest release package" >&2
    return 1
  fi
  pkg_path="$CACHE_DIR/$asset_name"
  if [[ ! -s "$pkg_path" ]]; then
    /usr/bin/curl -fL --retry 3 -o "$pkg_path.tmp" "$asset_url"
    /bin/mv "$pkg_path.tmp" "$pkg_path"
  fi
  /usr/sbin/pkgutil --check-signature "$pkg_path" >/tmp/helperai-virtual-hid-pkg-signature.txt
  cat <<INFO
{
  "ok": true,
  "tag": "$tag",
  "package": "$pkg_path",
  "signatureEvidence": "/tmp/helperai-virtual-hid-pkg-signature.txt",
  "nextInstallCommand": "$ROOT_DIR/bin/virtual-hid-setup install --i-understand-sudo --cache-dir '$CACHE_DIR'"
}
INFO
}

case "$ACTION" in
  status)
    exec "$DOCTOR"
    ;;

  prepare)
    download_pkg
    ;;

  install)
    if [[ "$ALLOW_SUDO" -ne 1 ]]; then
      cat >&2 <<MSG
virtual-hid-setup install requires explicit sudo approval.
It will run Apple's installer for the downloaded pqrs VirtualHID .pkg.
Re-run with: bin/virtual-hid-setup install --i-understand-sudo
MSG
      exit 64
    fi
    pkg_json="$(download_pkg)"
    pkg_path="$(printf '%s\n' "$pkg_json" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin)["package"])')"
    sudo_cmd /usr/sbin/installer -pkg "$pkg_path" -target /
    cat <<MSG
{
  "ok": true,
  "installedPackage": "$pkg_path",
  "nextStep": "Run bin/virtual-hid-setup activate --i-understand-sudo, approve the pqrs system extension in System Settings when prompted, then reboot only after explicit current-turn user approval."
}
MSG
    ;;

  activate)
    if [[ "$ALLOW_SUDO" -ne 1 ]]; then
      cat >&2 <<MSG
virtual-hid-setup activate requires explicit sudo approval.
It will run the pqrs VirtualHID manager activate command.
Re-run with: bin/virtual-hid-setup activate --i-understand-sudo
MSG
      exit 64
    fi
    if [[ ! -x "$MANAGER" ]]; then
      echo "virtual-hid-setup: manager not installed: $MANAGER" >&2
      echo "Run: bin/virtual-hid-setup install --i-understand-sudo" >&2
      exit 2
    fi
    sudo_cmd "$MANAGER" activate
    cat <<MSG
{
  "ok": true,
  "activated": "$MANAGER",
  "nextStep": "Approve the pqrs system extension in System Settings if macOS asks. Reboot is mandatory for full driver load, but this tool will not reboot without explicit current-turn user approval."
}
MSG
    ;;
esac
