#!/bin/bash
#
# Trust the Archipelago server's self-signed certificate on macOS.
# Run this to eliminate "Not secure" when accessing https://192.168.1.228
#
# Usage: ./scripts/trust-archipelago-cert.sh [host]
# Default host: 192.168.1.228
#
# Requires: SSH access to archipelago@host (uses deploy-config.sh password)
#

set -e

HOST="${1:-192.168.1.228}"
CERT_FILE="/tmp/archipelago-${HOST}.crt"
KEYCHAIN="${HOME}/Library/Keychains/login.keychain-db"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# Try to fetch cert from server via SSH (most reliable)
if [ -f "$SCRIPT_DIR/deploy-config.sh" ]; then
  . "$SCRIPT_DIR/deploy-config.sh"
  SSH_OPTS="-o StrictHostKeyChecking=no -o PreferredAuthentications=password -o PubkeyAuthentication=no"
  if command -v sshpass >/dev/null 2>&1; then
    echo "Fetching certificate from server..."
    sshpass -p "$ARCHIPELAGO_PASSWORD" ssh $SSH_OPTS archipelago@${HOST} \
      'sudo -n cat /etc/archipelago/ssl/archipelago.crt' > "$CERT_FILE" 2>/dev/null || true
  fi
fi

# Fallback: fetch via openssl (can hang on some systems)
if [ ! -s "$CERT_FILE" ]; then
  echo "Fetching certificate via TLS..."
  (echo "Q"; sleep 1) | openssl s_client -connect "${HOST}:443" -servername "${HOST}" 2>/dev/null | \
    openssl x509 -outform PEM > "$CERT_FILE"
fi

if [ ! -s "$CERT_FILE" ]; then
  echo "Failed to fetch certificate. Ensure deploy-config.sh exists and SSH works, or the server is reachable."
  exit 1
fi

echo "Adding to your login keychain..."

# Remove old cert if present (by common name)
security delete-certificate -c "archipelago.local" "$KEYCHAIN" 2>/dev/null || true

# Add to user keychain with trust (no sudo needed)
if security add-trusted-cert -d -r trustRoot -k "$KEYCHAIN" "$CERT_FILE" 2>/dev/null; then
  echo "   Certificate trusted successfully."
elif security add-trusted-cert -d -r trustAsRoot -k "$KEYCHAIN" "$CERT_FILE" 2>/dev/null; then
  echo "   Certificate trusted successfully."
else
  # Fallback: add cert and open Keychain Access for manual trust
  cp "$CERT_FILE" "$HOME/Desktop/archipelago-${HOST}.crt"
  echo ""
  echo "   Could not auto-trust. Certificate saved to Desktop."
  echo "   Double-click archipelago-${HOST}.crt to add it, then in Keychain Access"
  echo "   find it, double-click, expand Trust → set to 'Always Trust'."
  CERT_FILE=""  # Don't delete, we copied to Desktop
fi

rm -f "$CERT_FILE"

echo ""
echo "✅ Done. Restart your browser fully (quit Chrome/Safari) and visit https://${HOST}"
