#!/bin/sh
# Read-only macOS Post-Quantum Git & OpenSSH local diagnostic script.
# Emits JSON to stdout for pasting into /pq-monitor/ ("Verify your Mac locally").
# Performs zero network calls, zero file writes, and never reads private keys.

set -eu

json_escape() {
  printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr '\n' ' '
}

lines_to_json_array() {
  awk 'NF {
    gsub(/\\/, "\\\\");
    gsub(/"/, "\\\"");
    printf "%s\"%s\"", (n++ ? "," : ""), $0
  } END { if (!n) printf "" }'
}

inspect_ssh() {
  bin_path="$1"
  if [ ! -x "$bin_path" ]; then
    printf '{"present":false,"version":"","pqKeyAlgorithms":[],"pqKexAlgorithms":[]'
    return
  fi
  ver=$("$bin_path" -V 2>&1 | head -n 1 || true)
  keys=$("$bin_path" -Q key 2>/dev/null | grep -iE 'mldsa|slhdsa|dilithium|sphincs' | lines_to_json_array || true)
  kex=$("$bin_path" -Q kex 2>/dev/null | grep -iE 'mlkem|sntrup|kyber' | lines_to_json_array || true)
  printf '{"present":true,"version":"%s","pqKeyAlgorithms":[%s],"pqKexAlgorithms":[%s]' \
    "$(json_escape "$ver")" "$keys" "$kex"
}

apple_override=false
if [ -f /etc/ssh/crypto/apple.conf ] && grep -qE '^\s*KexAlgorithms\s+\^ecdh-' /etc/ssh/crypto/apple.conf 2>/dev/null; then
  apple_override=true
fi

mac_json="$(inspect_ssh /usr/bin/ssh),\"appleConfForcesClassicalKex\":$apple_override}"

brew_bin=""
if [ -x /opt/homebrew/bin/ssh ]; then
  brew_bin="/opt/homebrew/bin/ssh"
elif [ -x /usr/local/bin/ssh ]; then
  brew_bin="/usr/local/bin/ssh"
fi
if [ -n "$brew_bin" ]; then
  brew_json="$(inspect_ssh "$brew_bin")}"
else
  brew_json='{"present":false,"version":"","pqKeyAlgorithms":[],"pqKexAlgorithms":[]}'
fi

if command -v gpg >/dev/null 2>&1; then
  gpg_ver=$(gpg --version 2>/dev/null | head -n 1 | sed 's/gpg (GnuPG) //' || true)
  pub_raw=$(gpg --with-colons --list-config pubkeyname 2>/dev/null | sed 's/^cfg:pubkeyname://' | tr ';' '\n' || true)
  pub_arr=$(printf '%s\n' "$pub_raw" | lines_to_json_array)
  has_pq_sign=false
  if printf '%s\n' "$pub_raw" | grep -qiE 'mldsa|dilithium|slhdsa'; then
    has_pq_sign=true
  fi
  gpg_json=$(printf '{"present":true,"version":"%s","pubkeys":[%s],"hasPqSigning":%s}' \
    "$(json_escape "$gpg_ver")" "$pub_arr" "$has_pq_sign")
else
  gpg_json='{"present":false,"version":"","pubkeys":[],"hasPqSigning":false}'
fi

yk_present=false
yk_summary="No YubiKey OpenPGP card detected (or gpg-agent card-status unavailable)."
if command -v gpg >/dev/null 2>&1 && gpg --card-status >/dev/null 2>&1; then
  yk_present=true
  yk_summary="YubiKey / OpenPGP smart card detected; shipping YubiKey 5 OpenPGP supports classical RSA/ECC keys only."
fi

printf '{"macosOpenSsh":%s,"homebrewOpenSsh":%s,"gnupg":%s,"yubikey":{"present":%s,"summary":"%s"}}\n' \
  "$mac_json" "$brew_json" "$gpg_json" "$yk_present" "$(json_escape "$yk_summary")"
