#!/bin/bash

set -euo pipefail

PROJECT_ID="thunderbolts"
ORG_ID="xdev"
INSTALL_DIR="/usr/local/lib/${ORG_ID}/${PROJECT_ID}"
DOC_DIR="/usr/local/share/doc/${ORG_ID}/${PROJECT_ID}"
RECOVER_WRAPPER="/usr/local/sbin/tb-recover.sh"
UNINSTALL_WRAPPER="/usr/local/sbin/${ORG_ID}-${PROJECT_ID}-uninstall"
UDEV_RULE_PATH="/etc/udev/rules.d/90-thunderbolt-net-systemd.rules"
TB_BRIDGE_UNIT="/etc/systemd/system/tb-bridge.service"
TB_ENLIST_UNIT="/etc/systemd/system/tb-enlist@.service"
TB_RECOVER_UNIT="/etc/systemd/system/tb-recover.service"
TB_RECOVER_TIMER="/etc/systemd/system/tb-recover.timer"

FORCE_MODE=0

log() {
    if [[ "${FORCE_MODE}" -eq 0 ]]; then
        echo "$@"
    fi
}

require_root() {
    if [[ "${EUID}" -ne 0 ]]; then
        echo "ERROR: this script must be run as root" >&2
        exit 1
    fi
}

stop_enlist_instances() {
    local units
    units="$(systemctl list-units --all 'tb-enlist@*.service' --no-legend --no-pager 2>/dev/null | awk '{print $1}')"
    if [[ -n "${units}" ]]; then
        # shellcheck disable=SC2086
        systemctl stop ${units} >/dev/null 2>&1 || true
    fi
}

main() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --force)
                FORCE_MODE=1
                shift
                ;;
            -h|--help)
                echo "Usage: $0 [--force]"
                exit 0
                ;;
            *)
                echo "ERROR: unknown option: $1" >&2
                exit 1
                ;;
        esac
    done

    require_root

    log "=== Uninstalling ${PROJECT_ID} shared runtime ==="

    stop_enlist_instances
    systemctl disable --now tb-recover.timer >/dev/null 2>&1 || true
    systemctl stop tb-recover.service >/dev/null 2>&1 || true
    systemctl disable tb-bridge.service >/dev/null 2>&1 || true
    systemctl stop tb-bridge.service >/dev/null 2>&1 || true

    rm -f "${TB_RECOVER_TIMER}" "${TB_RECOVER_UNIT}" "${TB_ENLIST_UNIT}" "${TB_BRIDGE_UNIT}" "${UDEV_RULE_PATH}"
    rm -f "${UNINSTALL_WRAPPER}" "${RECOVER_WRAPPER}"
    rm -rf "${DOC_DIR}" "${INSTALL_DIR}"

    systemctl daemon-reload
    udevadm control --reload-rules

    rmdir /usr/local/lib/${ORG_ID} 2>/dev/null || true
    rmdir /usr/local/share/doc/${ORG_ID} 2>/dev/null || true

    log "Shared runtime removed."
    log "Network interface configuration was left untouched."
}

main "$@"
