#!/bin/bash
#
# DashCA Installer - Sami Home Network Root CA
# Installs the root CA certificate system-wide on Linux and macOS
#
# Usage: curl -fsSL https://ca.sami/install.sh | sudo bash
#
set -e

# Configuration
CERT_URL="https://ca.sami/root.crt"
EXPECTED_FP="08:98:A5:63:F5:A1:A2:58:5F:02:D7:A8:A2:54:87:E6:BC:33:96:9F:9B:5D:B0:53:62:20:7F:AF:96:21:29:0E"
CERT_NAME="Sami_Home_Network_Root_CA"

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

echo ""
echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN} DashCA Installer${NC}"
echo -e "${CYAN} Sami Home Network Root CA${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""

# Check for root/sudo
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}✗ This script requires root privileges${NC}"
   echo ""
   echo "Please run with sudo:"
   echo -e "  ${YELLOW}curl -fsSL https://ca.sami/install.sh | sudo bash${NC}"
   echo ""
   echo "Or download first, then run:"
   echo -e "  ${YELLOW}curl -o install.sh https://ca.sami/install.sh${NC}"
   echo -e "  ${YELLOW}sudo bash install.sh${NC}"
   echo ""
   exit 1
fi

# Detect OS
echo -e "${CYAN}[1/6] Detecting operating system...${NC}"
if [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macos"
    OS_NAME="macOS"
elif [[ -f /etc/os-release ]]; then
    . /etc/os-release
    if [[ "$ID" == "debian" ]] || [[ "$ID" == "ubuntu" ]] || [[ "$ID_LIKE" == *"debian"* ]]; then
        OS="debian"
        OS_NAME="Debian/Ubuntu"
    elif [[ "$ID" == "fedora" ]] || [[ "$ID" == "rhel" ]] || [[ "$ID" == "centos" ]] || [[ "$ID_LIKE" == *"fedora"* ]] || [[ "$ID_LIKE" == *"rhel"* ]]; then
        OS="redhat"
        OS_NAME="RedHat/CentOS/Fedora"
    elif [[ "$ID" == "arch" ]] || [[ "$ID_LIKE" == *"arch"* ]]; then
        OS="arch"
        OS_NAME="Arch Linux"
    else
        OS="unknown"
        OS_NAME="Unknown Linux"
    fi
elif [[ -f /etc/redhat-release ]]; then
    OS="redhat"
    OS_NAME="RedHat/CentOS"
elif [[ -f /etc/arch-release ]]; then
    OS="arch"
    OS_NAME="Arch Linux"
else
    OS="unknown"
    OS_NAME="Unknown"
fi

if [[ "$OS" == "unknown" ]]; then
    echo -e "${RED}      ✗ Unsupported operating system${NC}"
    echo ""
    echo "This script supports:"
    echo "  - Debian/Ubuntu"
    echo "  - RedHat/CentOS/Fedora"
    echo "  - Arch Linux"
    echo "  - macOS"
    echo ""
    echo "For manual installation, download the certificate:"
    echo -e "  ${YELLOW}curl -O $CERT_URL${NC}"
    echo ""
    exit 1
fi

echo -e "${GREEN}      ✓ Detected: $OS_NAME${NC}"

# Download certificate
echo -e "${CYAN}[2/6] Downloading certificate from $CERT_URL...${NC}"
TEMP_CERT=$(mktemp)
if ! curl -fsSL "$CERT_URL" -o "$TEMP_CERT"; then
    echo -e "${RED}      ✗ Failed to download certificate${NC}"
    echo ""
    echo -e "${YELLOW}Troubleshooting:${NC}"
    echo "  - Ensure you are on the Tailnet/network where ca.sami is accessible"
    echo "  - Try accessing https://ca.sami in your browser first"
    echo "  - Check your network connection"
    rm -f "$TEMP_CERT"
    exit 1
fi
echo -e "${GREEN}      ✓ Certificate downloaded${NC}"

# Verify fingerprint
echo -e "${CYAN}[3/6] Verifying certificate fingerprint...${NC}"
if ! command -v openssl &> /dev/null; then
    echo -e "${RED}      ✗ OpenSSL not found${NC}"
    echo "Please install OpenSSL to verify certificate fingerprint"
    rm -f "$TEMP_CERT"
    exit 1
fi

ACTUAL_FP=$(openssl x509 -in "$TEMP_CERT" -noout -fingerprint -sha256 | cut -d= -f2)

if [[ "$ACTUAL_FP" != "$EXPECTED_FP" ]]; then
    echo -e "${RED}      ✗ Fingerprint mismatch!${NC}"
    echo -e "${YELLOW}        Expected: $EXPECTED_FP${NC}"
    echo -e "${RED}        Got:      $ACTUAL_FP${NC}"
    rm -f "$TEMP_CERT"
    echo ""
    echo -e "${RED}SECURITY WARNING: The downloaded certificate does not match the expected fingerprint.${NC}"
    echo -e "${RED}This could indicate a man-in-the-middle attack or certificate renewal.${NC}"
    echo -e "${RED}Please verify with your network administrator before proceeding.${NC}"
    echo ""
    exit 1
fi

echo -e "${GREEN}      ✓ Fingerprint verified${NC}"

# Extract certificate details
echo -e "${CYAN}[4/6] Extracting certificate information...${NC}"
CERT_SUBJECT=$(openssl x509 -in "$TEMP_CERT" -noout -subject | sed 's/subject=//')
CERT_NOT_AFTER=$(openssl x509 -in "$TEMP_CERT" -noout -enddate | sed 's/notAfter=//')
echo -e "${GREEN}      ✓ Subject: $CERT_SUBJECT${NC}"
echo -e "${GREEN}      ✓ Valid until: $CERT_NOT_AFTER${NC}"

# Check if already installed
echo -e "${CYAN}[5/6] Checking for existing installation...${NC}"
ALREADY_INSTALLED=false

case "$OS" in
    debian)
        if [[ -f "/usr/local/share/ca-certificates/${CERT_NAME}.crt" ]]; then
            ALREADY_INSTALLED=true
        fi
        ;;
    redhat)
        if [[ -f "/etc/pki/ca-trust/source/anchors/${CERT_NAME}.crt" ]]; then
            ALREADY_INSTALLED=true
        fi
        ;;
    arch)
        if [[ -f "/etc/ca-certificates/trust-source/anchors/${CERT_NAME}.crt" ]]; then
            ALREADY_INSTALLED=true
        fi
        ;;
    macos)
        if security find-certificate -a -c "$CERT_SUBJECT" /Library/Keychains/System.keychain &>/dev/null; then
            ALREADY_INSTALLED=true
        fi
        ;;
esac

if [[ "$ALREADY_INSTALLED" == "true" ]]; then
    echo -e "${YELLOW}      ℹ Certificate already installed${NC}"
    rm -f "$TEMP_CERT"
    echo ""
    echo -e "${GREEN}The Sami Home Network Root CA is already trusted on this system.${NC}"
    echo -e "${GREEN}No further action needed!${NC}"
    echo ""
    exit 0
fi

echo -e "${GREEN}      ✓ Certificate not yet installed, proceeding...${NC}"

# Install based on OS
echo -e "${CYAN}[6/6] Installing certificate...${NC}"
case "$OS" in
    debian)
        cp "$TEMP_CERT" "/usr/local/share/ca-certificates/${CERT_NAME}.crt"
        update-ca-certificates
        echo -e "${GREEN}      ✓ Certificate installed via update-ca-certificates${NC}"
        ;;
    redhat)
        cp "$TEMP_CERT" "/etc/pki/ca-trust/source/anchors/${CERT_NAME}.crt"
        update-ca-trust
        echo -e "${GREEN}      ✓ Certificate installed via update-ca-trust${NC}"
        ;;
    arch)
        cp "$TEMP_CERT" "/etc/ca-certificates/trust-source/anchors/${CERT_NAME}.crt"
        trust extract-compat
        echo -e "${GREEN}      ✓ Certificate installed via trust extract-compat${NC}"
        ;;
    macos)
        security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$TEMP_CERT"
        echo -e "${GREEN}      ✓ Certificate installed to System Keychain${NC}"
        ;;
esac

# Cleanup
rm -f "$TEMP_CERT"

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN} SUCCESS!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${GREEN}The Sami Home Network Root CA has been installed system-wide.${NC}"
echo ""
echo -e "${CYAN}What's next:${NC}"
echo -e "  ${GREEN}✓${NC} All *.sami domains will now be trusted"
echo -e "  ${GREEN}✓${NC} Browsers will no longer show security warnings"
echo -e "  ${GREEN}✓${NC} Applications will trust HTTPS connections to your local services"
echo ""
echo -e "${CYAN}Test it out:${NC}"
echo -e "  ${YELLOW}Visit https://status.sami or any other *.sami service${NC}"
echo -e "  ${YELLOW}The connection should show as secure with no warnings${NC}"
echo ""
