#!/bin/sh
set -e

CA_NICKNAME="Bnhmeijer Homelab Root CA"

case "$1" in
    remove|purge|disappear)
        # 1. Update OS system trust store
        if command -v update-ca-certificates >/dev/null 2>&1; then
            echo "Verwijderen van certificaat uit systeem trust store..."
            update-ca-certificates --fresh >/dev/null 2>&1 || true
        fi

        # 2. Clean up Firefox symlink if it points to our policy
        if [ -L /usr/lib/firefox/distribution/policies.json ]; then
            rm -f /usr/lib/firefox/distribution/policies.json 2>/dev/null || true
        fi

        # 3. Remove from NSS databases if certutil is installed
        if command -v certutil >/dev/null 2>&1; then
            for user_home in /root $(awk -F: '$3 >= 1000 && $3 < 60000 {print $6}' /etc/passwd 2>/dev/null); do
                for pki_dir in "$user_home/.pki/nssdb" "$user_home/.local/share/pki/nssdb"; do
                    if [ -d "$pki_dir" ]; then
                        certutil -d "sql:$pki_dir" -D -n "$CA_NICKNAME" >/dev/null 2>&1 || true
                    fi
                done
            done
        fi
    ;;
esac
exit 0
