#!/usr/bin/env bash

set -euo pipefail

declare -r CERTURL="https://x509.kompfix.online/certs/latest.pem"
declare -r CERTSHA="E2:FD:DB:57:D0:99:41:E9:43:E3:C3:DB:09:3D:9C:7D:AF:25:A8:3A:81:57:64:36:25:F0:1D:D9:A5:2D:96:B7"
declare -r CERTNAME="local_network_ca"

function die() {
    echo -e "\e[1;31merror: $*\e[0m" >&2
    exit 1
}

[ "$EUID" -ne 0 ] && die "Please run this script as root"
[ ! -f "/etc/os-release" ] && die "Missing os-release file"

declare -r distro=$(source /etc/os-release && echo "$ID")

certs_dir=""
update_command=""

case "$distro" in
    arch)
        certs_dir="/etc/ca-certificates/trust-source/anchors"
        update_command="update-ca-trust"
        ;;

    debian | ubuntu)
        certs_dir="/usr/local/share/ca-certificates"
        update_command="update-ca-certificates"
        ;;

    fedora | rhel)
        certs_dir="/etc/pki/ca-trust/source/anchors"
        update_command="update-ca-trust"
        ;;

    opensuse-tumbleweed | opensuse-leap)
        certs_dir="/etc/pki/trust/anchors"
        update_command="update-ca-certificates"
        ;;

    *) die "Unknown Linux distro: $distro" ;;
esac

if ! command -v "$update_command" &> /dev/null; then
    die "Command $update_command not found"
fi

[ ! -d "$certs_dir" ] && die "Directory $certs_dir does not exist"

declare -r cert_file="$certs_dir/$CERTNAME.crt"

function install_certificate() {
    echo "Installing certificate to $cert_file..."

    declare -r tempdir=$(mktemp -d)
    declare -r tempfile="$tempdir/$CERTNAME.crt"
    trap 'rm -rf "$tempdir"' RETURN

    echo "Downloading latest PEM..."
    echo "  URL: $CERTURL"
    echo "  SHA-256 Fingerprint: $CERTSHA"

    curl -fsSL -o "$tempfile" "$CERTURL"

    echo "Validating SHA-256 fingerprint..."
    declare -r sha256=$(openssl x509 -noout -fingerprint -sha256 -in "$tempfile" | cut -d= -f2 | tr '[:lower:]' '[:upper:]')

    if [ "$sha256" != "$CERTSHA" ]; then
        die "Fingerprint validation failed! Expected $CERTSHA, got $sha256"
    fi

    echo "Fingerprint validation OK"

    [ -f "$cert_file" ] && rm "$cert_file"
    cp "$tempfile" "$cert_file"
    "$update_command"

    echo -e "\e[1;32mSuccessfully installed certificate\e[0m"
}

function uninstall_certificate() {
    echo "Uninstalling certificate from $cert_file..."

    [ ! -f "$cert_file" ] && die "File $cert_file does not exist, nothing to remove"
    rm "$cert_file"
    "$update_command"

    echo -e "\e[1;32mSuccessfully uninstalled certificate\e[0m"
}

function select_action() {
    if [ -t 0 ]; then
        exec 3<&0
    elif ! exec 3</dev/tty 2> /dev/null; then
        die "No terminal available to read the option, use 'install' or 'uninstall' argument instead"
    fi

    while true; do
        printf "Select option: "

        declare choice=""
        if ! IFS= read -r choice <&3; then
            echo
            die "Failed to read the option, aborting"
        fi

        case "$choice" in
            1)
                install_certificate
                return
                ;;
            2)
                uninstall_certificate
                return
                ;;
            *)
                echo "Invalid option: $choice"
                ;;
        esac
    done
}

case "${1:-}" in
    install)
        install_certificate
        ;;

    uninstall)
        uninstall_certificate
        ;;

    "")
        if [ -f "$cert_file" ]; then
            echo "Certificate is already installed."
            echo "1) Upgrade certificate"
            echo "2) Uninstall certificate"
            select_action
        else
            install_certificate
        fi
        ;;

    *) die "Invalid command, must be install or uninstall" ;;
esac
