#!/bin/bash
set -e

# Root-Check
if [ "$EUID" -ne 0 ]; then 
  echo "Bitte als root ausführen (sudo)."
  exit 1
fi

echo "Lade CA herunter und installiere sie im System..."
cd /tmp
wget -nv -O /tmp/ca.crt https://web.samogo.de/certs/ca.crt
install -m 644 /tmp/ca.crt /usr/local/share/ca-certificates/kit-ca.crt
update-ca-certificates

# Die Policy als Variable (vermeidet Redundanz)
POLICY_JSON='{
  "policies": {
    "Certificates": {
      "ImportEnterpriseRoots": true
    }
  }
}'

# Funktion zum Setzen der Policy für Mozilla-Produkte
set_mozilla_policy() {
    local app_name=$1
    local bin_name=$2
    
    if command -v "$bin_name" >/dev/null 2>&1; then
        echo "Setze Policies für $app_name..."
        
        # Pfad 1: Der Debian /etc Standard
        mkdir -p "/etc/$bin_name/policies"
        echo "$POLICY_JSON" > "/etc/$bin_name/policies/policies.json"
        
        # Pfad 2: Der Distribution-Pfad (wichtig für Debian ESR Versionen)
        # Wir suchen den Pfad, wo die Binärdatei liegt (meist /usr/lib/firefox-esr)
        local lib_path="/usr/lib/$bin_name"
        if [ -d "$lib_path" ]; then
            mkdir -p "$lib_path/distribution"
            echo "$POLICY_JSON" > "$lib_path/distribution/policies.json"
        fi
        
        pkill -9 "$bin_name" 2>/dev/null || true
    fi
}

# Firefox (ESR und Standard)
set_mozilla_policy "Firefox" "firefox"
set_mozilla_policy "Firefox-ESR" "firefox-esr"

# Thunderbird
set_mozilla_policy "Thunderbird" "thunderbird"

echo "------------------------------------------------"
echo "CA installiert und Policies auf alle Pfade angewendet."
echo "Bitte Firefox/Thunderbird neu starten und about:policies prüfen."
