#!/usr/bin/env bash
# ---------------------------------------------------------------------------
# install-captured-ca.sh - trust the CAs captured by check-ssl.sh
#
#   bash install-captured-ca.sh <ssl-report-dir>
#
# Installs every captured CA that is NOT already a public root into:
#   1. the system trust store   (/usr/local/share/ca-certificates/corp)
#      -> fixes curl, git, python, openssl
#   2. /usr/local/share/corp-bundle.pem
#      -> fixes node AND opencode (Bun ignores the system store and
#         SSL_CERT_FILE; it only honours NODE_EXTRA_CA_CERTS)
# ---------------------------------------------------------------------------
set -euo pipefail

REPORT_DIR="${1:-}"
[ -n "$REPORT_DIR" ] || { echo "usage: bash install-captured-ca.sh <ssl-report-dir>"; exit 1; }
CAS="$REPORT_DIR/captured-cas"
[ -d "$CAS" ] || { echo "no captured-cas/ inside $REPORT_DIR"; exit 1; }

SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO="sudo"
DEST=/usr/local/share/ca-certificates/corp
CORP_BUNDLE=/usr/local/share/corp-bundle.pem
SYS_BUNDLE=/etc/ssl/certs/ca-certificates.crt

PUBLIC_RE='digicert|globalsign|let.?s encrypt|isrg|google trust|amazon|sectigo|comodo|baltimore|entrust|godaddy|usertrust|verisign|thawte|geotrust|certum|buypass|identrust'

echo "==> Selecting non-public CAs from $CAS"
$SUDO mkdir -p "$DEST"
TMP_BUNDLE="$(mktemp)"
declare -A SEEN
n=0

for f in "$CAS"/*.pem; do
  [ -e "$f" ] || continue
  SUBJ="$(openssl x509 -in "$f" -noout -subject 2>/dev/null | sed 's/^subject= *//')" || continue
  [ -n "$SUBJ" ] || continue

  if echo "$SUBJ" | grep -qiE "$PUBLIC_RE"; then
    echo "    skip (public CA): $SUBJ"
    continue
  fi

  FP="$(openssl x509 -in "$f" -noout -fingerprint -sha256 | cut -d= -f2)"
  if [ -n "${SEEN[$FP]:-}" ]; then continue; fi
  SEEN[$FP]=1

  # filename from CN, sanitised
  CN="$(echo "$SUBJ" | sed 's/.*CN *= *//; s/,.*//' | tr -c 'A-Za-z0-9._-' '_' | sed 's/_*$//')"
  SHORT="${FP//:/}"; SHORT="${SHORT:0:8}"
  NAME="${CN}_${SHORT}"

  echo "    [+] $SUBJ"
  echo "        -> $DEST/${NAME}.crt"
  openssl x509 -in "$f" | $SUDO tee "$DEST/${NAME}.crt" >/dev/null

  {
    echo "# Subject: $SUBJ"
    echo "# Issuer : $(openssl x509 -in "$f" -noout -issuer | sed 's/^issuer= *//')"
    echo "# Expires: $(openssl x509 -in "$f" -noout -enddate | cut -d= -f2)"
    openssl x509 -in "$f"
    echo
  } >> "$TMP_BUNDLE"
  n=$((n+1))
done

[ "$n" -gt 0 ] || { echo "No non-public CAs found - nothing to install."; rm -f "$TMP_BUNDLE"; exit 1; }

echo "==> Updating system trust store ($n certificate(s))"
$SUDO update-ca-certificates

echo "==> Writing $CORP_BUNDLE (for NODE_EXTRA_CA_CERTS / Bun / opencode)"
$SUDO cp "$TMP_BUNDLE" "$CORP_BUNDLE"
$SUDO chmod 644 "$CORP_BUNDLE"
rm -f "$TMP_BUNDLE"

echo "==> Making env vars available to non-login shells too"
SNIPPET=/etc/profile.d/corp-ca.sh
$SUDO tee "$SNIPPET" >/dev/null <<EOF
export SSL_CERT_FILE=${SYS_BUNDLE}
export REQUESTS_CA_BUNDLE=${SYS_BUNDLE}
export CURL_CA_BUNDLE=${SYS_BUNDLE}
export NODE_EXTRA_CA_CERTS=${CORP_BUNDLE}
export AWS_CA_BUNDLE=${SYS_BUNDLE}
EOF
$SUDO chmod 644 "$SNIPPET"

if ! grep -q 'profile.d/corp-ca.sh' "$HOME/.bashrc" 2>/dev/null; then
  printf '\n# corporate CA trust (also for non-login shells)\n[ -r %s ] && . %s\n' "$SNIPPET" "$SNIPPET" >> "$HOME/.bashrc"
  echo "    added source line to ~/.bashrc"
else
  echo "    ~/.bashrc already sources it"
fi

echo "==> Configuring git / npm"
git config --global http.sslCAInfo "$SYS_BUNDLE" 2>/dev/null || true
command -v npm >/dev/null 2>&1 && npm config set cafile "$CORP_BUNDLE" 2>/dev/null || true

echo
echo "Done. $n corporate CA(s) installed."
echo "System bundle now has $(grep -c 'BEGIN CERTIFICATE' "$SYS_BUNDLE") certificates."
echo
echo "Open a NEW shell, then verify ON THE CORPORATE WLAN:"
echo "  curl -sSI https://models.opencode.ai/api.json | head -1"
echo "  opencode run 'hi'"
