#!/usr/bin/env bash
# ============================================================
#  ZWServe HTTPS cert installer — Linux
#  Installs zwserver.crt into the system CA trust store so
#  browsers/tools trust https://127.0.0.1 and https://localhost.
#  Supports Debian/Ubuntu, Fedora/RHEL, Arch, openSUSE.
#  Requires sudo.
# ============================================================
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 "Installing \"$CRT\" into the system CA trust store ..."

# Debian / Ubuntu (and derivatives)
if [ -d /usr/local/share/ca-certificates ]; then
    install -m 644 "$CRT" /usr/local/share/ca-certificates/zwserver.crt
    # update-ca-certificates expects a .crt with this extension on Debian.
    update-ca-certificates
    INSTALLED=1
fi

# Fedora / RHEL / CentOS / Arch / openSUSE (uses the consolidated bundle)
if command -v update-ca-trust >/dev/null 2>&1; then
    install -m 644 "$CRT" /etc/pki/ca-trust/source/anchors/zwserver.crt 2>/dev/null || \
        install -m 644 "$CRT" /etc/ca-certificates/trust-source/anchors/zwserver.crt 2>/dev/null || true
    update-ca-trust extract
    INSTALLED=1
fi

if [ "${INSTALLED:-0}" != "1" ]; then
    echo "[ERROR] Could not detect a supported CA trust store layout."
    echo "Manually copy zwserver.crt into your distro's CA directory and run its update tool."
    exit 1
fi

echo ""
echo "=== DONE ==="
echo "The ZWServe local cert is now trusted (system tools/curl)."
echo "Start ZWServe with:  ./zwserv-linux -https"
echo "Then open https://127.0.0.1:8000/ — no certificate warning."
echo ""
echo "NOTE: Some Linux browsers (Firefox) keep their own trust store."
echo "  Firefox: Preferences > Privacy & Security > Certificates > View Certificates > Authorities > Import > zwserver.crt"
