#!/usr/bin/env bash
set -euo pipefail

# ==========================================
# CONFIGURATION (Injected by DashCaddy API)
# ==========================================
CERT_URL="{{CERT_URL}}"
EXPECTED_FP="{{CERT_FINGERPRINT}}"
# ==========================================

TMPFILE="$(mktemp /tmp/dashcaddy-root-ca.XXXXXX.crt)"

RED='\033[0;31m'; GREEN='\033[0;32m'; CYAN='\033[0;36m'; YELLOW='\033[1;33m'; NC='\033[0m'

echo ""
echo -e "${CYAN}========================================"
echo " DashCaddy Certificate Installer"
echo -e "========================================${NC}"
echo ""

# Step 1: Download certificate (skip TLS verification — we verify the fingerprint instead)
echo -e "${CYAN}[1/4] Downloading certificate...${NC}"
if command -v curl &>/dev/null; then
    curl -fsSk -o "$TMPFILE" "$CERT_URL"
elif command -v wget &>/dev/null; then
    wget -q --no-check-certificate -O "$TMPFILE" "$CERT_URL"
else
    echo -e "${RED}      FAIL  Neither curl nor wget found${NC}"
    exit 1
fi
echo -e "${GREEN}      OK  Certificate downloaded${NC}"

# Step 2: Verify fingerprint
echo -e "${CYAN}[2/4] Verifying certificate fingerprint...${NC}"
ACTUAL_FP=$(openssl x509 -in "$TMPFILE" -noout -fingerprint -sha256 2>/dev/null | sed 's/.*=//; s/://g')
CLEAN_EXPECTED=$(echo "$EXPECTED_FP" | tr -d ': ')

if [ "$ACTUAL_FP" != "$CLEAN_EXPECTED" ]; then
    echo -e "${RED}      FAIL  Fingerprint mismatch!${NC}"
    echo -e "${YELLOW}        Expected: $EXPECTED_FP${NC}"
    echo -e "${RED}        Got:      $ACTUAL_FP${NC}"
    rm -f "$TMPFILE"
    echo -e "${RED}SECURITY WARNING: Certificate does not match expected fingerprint.${NC}"
    exit 1
fi
echo -e "${GREEN}      OK  Fingerprint verified${NC}"

# Step 3: Detect OS and install
echo -e "${CYAN}[3/4] Installing certificate...${NC}"

install_debian() {
    sudo cp "$TMPFILE" /usr/local/share/ca-certificates/dashcaddy-root-ca.crt
    sudo update-ca-certificates
}

install_redhat() {
    sudo cp "$TMPFILE" /etc/pki/ca-trust/source/anchors/dashcaddy-root-ca.crt
    sudo update-ca-trust extract
}

install_arch() {
    sudo cp "$TMPFILE" /etc/ca-certificates/trust-source/anchors/dashcaddy-root-ca.crt
    sudo trust extract-compat
}

install_macos() {
    sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$TMPFILE"
}

if [ "$(uname)" = "Darwin" ]; then
    install_macos
elif [ -f /etc/debian_version ]; then
    install_debian
elif [ -f /etc/redhat-release ]; then
    install_redhat
elif [ -f /etc/arch-release ]; then
    install_arch
elif command -v update-ca-certificates &>/dev/null; then
    install_debian
elif command -v update-ca-trust &>/dev/null; then
    install_redhat
else
    echo -e "${RED}      FAIL  Could not detect package manager. Install manually:${NC}"
    echo "        Copy $TMPFILE to your system's CA trust store"
    exit 1
fi
echo -e "${GREEN}      OK  Certificate installed${NC}"

# Step 4: Cleanup
rm -f "$TMPFILE"

echo ""
echo -e "${GREEN}========================================"
echo " SUCCESS!"
echo -e "========================================${NC}"
echo ""
echo -e "${GREEN}Your system now trusts the DashCaddy Root CA.${NC}"
echo -e "${YELLOW}Restart your browser for changes to take effect.${NC}"
echo ""
