#!/usr/bin/env bash
# ============================================================================
# install-macos.sh — Install GWS device certificate on macOS
#
# Usage:
#   ./install-macos.sh /path/to/cert.p12
#   ./install-macos.sh /path/to/cert.p12 /path/to/ca.crt
#
# What it does:
#   1. Imports .p12 client cert to login keychain (current user)
#   2. Imports CA cert to System keychain (requires sudo)
# ============================================================================
set -euo pipefail

P12_PATH="${1:?Usage: $0 /path/to/cert.p12 [/path/to/ca.crt]}"
CA_PATH="${2:-}"

echo ""
echo "========================================"
echo "  GWS Cert Installer - macOS"
echo "========================================"
echo ""

if [[ ! -f "$P12_PATH" ]]; then
  echo "[ERROR] File not found: $P12_PATH"
  exit 1
fi

# --- Step 1: Import client cert to login keychain ---
echo "[1/2] Importing client certificate to login keychain..."
echo "Enter the .p12 import password (leave empty if none):"
read -s P12_PASS
echo ""

security import "$P12_PATH" \
  -k "$HOME/Library/Keychains/login.keychain-db" \
  -P "$P12_PASS" \
  -T /usr/bin/codesign \
  -T /usr/bin/security \
  -T "/Applications/Google Chrome.app" \
  2>/dev/null && echo "  OK: Client cert imported to login keychain" || {
    echo "[ERROR] Import failed. Check your password."
    exit 1
  }

# --- Step 2: Import CA cert (if provided) ---
if [[ -n "$CA_PATH" && -f "$CA_PATH" ]]; then
  echo "[2/2] Importing CA certificate to System keychain (requires sudo)..."
  sudo security add-trusted-cert -d -r trustRoot \
    -k /Library/Keychains/System.keychain "$CA_PATH" \
    && echo "  OK: CA cert added to System keychain" \
    || echo "  WARN: Could not import CA cert"
else
  echo "[2/2] No CA cert provided, skipping."
fi

echo ""
echo "Done! Restart Chrome/Safari to use the certificate."
echo ""
echo "To verify: Keychain Access → login → look for your cert"
echo ""
