#!/usr/bin/env bash
set -euo pipefail

AUTHKEY=""
SSH_PUBKEY=""
USERNAME="hermesops"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --authkey) AUTHKEY="$2"; shift 2 ;;
    --ssh-pubkey) SSH_PUBKEY="$2"; shift 2 ;;
    --username) USERNAME="$2"; shift 2 ;;
    *) echo "unknown arg: $1" >&2; exit 1 ;;
  esac
 done

[[ -n "$AUTHKEY" ]] || { echo "missing --authkey" >&2; exit 1; }
[[ -n "$SSH_PUBKEY" ]] || { echo "missing --ssh-pubkey" >&2; exit 1; }

if ! command -v tailscale >/dev/null 2>&1; then
  brew install --cask tailscale
fi

if ! pgrep -x tailscaled >/dev/null 2>&1; then
  open -a Tailscale || true
fi

sudo tailscale up --authkey "$AUTHKEY" --hostname "$(hostname)-incident" || true
sudo systemsetup -setremotelogin on || true

if ! id "$USERNAME" >/dev/null 2>&1; then
  echo "Create a dedicated user through macOS UI/MDM for production; using existing admin account for bootstrap only."
fi

sudo mkdir -p /opt/hermes-remote
sudo tee /opt/hermes-remote/diagnose.sh >/dev/null <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
TS="$(date -u +%Y%m%dT%H%M%SZ)"
HOST="$(hostname)"
OUT="/tmp/hermes-diagnose-${HOST}-${TS}"
mkdir -p "$OUT"

run() {
  name="$1"; shift
  {
    echo "### $name"
    echo "### command: $*"
    "$@" 2>&1 || true
  } > "$OUT/$name.txt"
}

run sw_vers sw_vers
run uname uname -a
run uptime uptime
run date date -u
run tailscale_status tailscale status
run tailscale_netcheck tailscale netcheck
run pmset pmset -g everything
run diskutil_list diskutil list
run df df -h
run ifconfig ifconfig
run netstat netstat -rn
run system_profiler_basic system_profiler SPHardwareDataType SPSoftwareDataType SPStorageDataType SPPowerDataType
run log_panic log show --predicate 'eventMessage CONTAINS[c] "panic" OR eventMessage CONTAINS[c] "shutdown" OR eventMessage CONTAINS[c] "previous shutdown cause"' --last 14d
run log_errors log show --predicate 'messageType == "error" OR messageType == "fault"' --last 3d

cp -a /Library/Logs/DiagnosticReports "$OUT/DiagnosticReports" 2>/dev/null || true
cp -a "$HOME/Library/Logs/DiagnosticReports" "$OUT/UserDiagnosticReports" 2>/dev/null || true

tar -C /tmp -czf "${OUT}.tar.gz" "$(basename "$OUT")"
echo "${OUT}.tar.gz"
EOF
sudo chmod 755 /opt/hermes-remote/diagnose.sh

echo "OK"
