#!/usr/bin/env bash
# ============================================================
#  ZWServe HTTPS cert installer — macOS
#  Adds zwserver.crt to the System keychain as a trusted root so
#  browsers/tools trust https://127.0.0.1 and https://localhost.
#  Requires sudo (writes to /Library/Keychains/System.keychain).
# ============================================================
set -euo pipefail

CRT="$(cd "$(dirname "$0")" && pwd)/zwserver.crt"

if [ ! -f "$CRT" ]; then
    echo "[ERROR] zwserver.crt not found next to this script."
    echo "Expected: $CRT"
    exit 1
fi

# Re-run with sudo if not root.
if [ "$(id -u)" -ne 0 ]; then
    echo "This needs administrator access. Re-running with sudo ..."
    exec sudo "$0" "$@"
fi

echo "Adding \"$CRT\" to System keychain as a trusted root ..."
# -d  : add to the specified (System) keychain instead of the login one
# -t  : mark as trusted
# /Library/Keychains/System.keychain : affects all users / all browsers
security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$CRT"

echo ""
echo "=== DONE ==="
echo "The ZWServe local cert is now trusted."
echo "Start ZWServe with:  ./zwserv-macos -https"
echo "Then open https://127.0.0.1:8000/ — no certificate warning."
