#!/bin/bash

set -euo pipefail

PROJECT_ID="pve-guests-state"
ORG_ID="xdev"
INSTALL_DIR="/usr/local/lib/${ORG_ID}/${PROJECT_ID}"
DOC_DIR="/usr/local/share/doc/${ORG_ID}/${PROJECT_ID}"
STATE_DIR="/var/lib/${ORG_ID}/${PROJECT_ID}"
STATE_FILE="${STATE_DIR}/pgs-state.json"
COMMAND_PATH="/usr/local/sbin/pgs"
UNINSTALL_WRAPPER="/usr/local/sbin/${ORG_ID}-${PROJECT_ID}-uninstall"

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
}

cleanup_legacy_artifacts() {
    rm -f /usr/local/sbin/pve-reboot-manager.sh
    rm -f /usr/local/sbin/pve-guest-state.sh
    rm -f /root/bin/pgs
    rm -f /root/bin/pve-reboot-manager.sh
    rm -f /root/bin/pve-guest-state.sh

    rm -f /var/lib/pve-manager/pgs-state.json
    rm -f /var/lib/pve-manager/guest-state.json
    rm -f /var/lib/pve-manager/reboot-vm-state.json
}

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} ==="

    systemctl disable pve-suspend-vms.service pve-resume-vms.service >/dev/null 2>&1 || true
    systemctl stop pve-suspend-vms.service pve-resume-vms.service >/dev/null 2>&1 || true
    rm -f /etc/systemd/system/pve-suspend-vms.service
    rm -f /etc/systemd/system/pve-resume-vms.service
    systemctl daemon-reload
    systemctl reset-failed pve-suspend-vms.service pve-resume-vms.service >/dev/null 2>&1 || true

    rm -f "${UNINSTALL_WRAPPER}"
    rm -f "${COMMAND_PATH}"
    rm -f "${STATE_FILE}"
    rm -rf "${DOC_DIR}"
    rm -rf "${INSTALL_DIR}"
    rm -rf "${STATE_DIR}"

    cleanup_legacy_artifacts

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

    log "Uninstall complete."
}

main "$@"
