#!/bin/bash

set -euo pipefail

PROJECT_ID="pve-net-hang-watchdog"
ORG_ID="xdev"
INSTALL_DIR="/usr/local/lib/${ORG_ID}/${PROJECT_ID}"
DOC_DIR="/usr/local/share/doc/${ORG_ID}/${PROJECT_ID}"
COMMAND_PATH="/usr/local/sbin/pve-net-hang-watchdog.sh"
UNINSTALL_PATH="${INSTALL_DIR}/uninstall.sh"
UNINSTALL_WRAPPER="/usr/local/sbin/${ORG_ID}-${PROJECT_ID}-uninstall"
CONFIG_PATH="/etc/default/${ORG_ID}-${PROJECT_ID}"
UNIT_PATH="/etc/systemd/system/${PROJECT_ID}.service"

SOURCE_DIR=""

usage() {
    cat <<EOF
Usage: $0 [--source-dir <path>]

Install ${PROJECT_ID} on the current host.
EOF
}

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

resolve_source_dir() {
    if [[ -n "${SOURCE_DIR}" ]]; then
        SOURCE_DIR="$(cd "${SOURCE_DIR}" && pwd)"
    else
        SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
    fi
}

validate_source_tree() {
    local required_files=(
        "${SOURCE_DIR}/bin/pve-net-hang-watchdog.sh"
        "${SOURCE_DIR}/systemd/pve-net-hang-watchdog.service"
        "${SOURCE_DIR}/config/xdev-pve-net-hang-watchdog"
        "${SOURCE_DIR}/scripts/uninstall.sh"
        "${SOURCE_DIR}/README.md"
        "${SOURCE_DIR}/INSTALL.md"
        "${SOURCE_DIR}/CHANGELOG.md"
    )
    local file=""
    for file in "${required_files[@]}"; do
        if [[ ! -f "${file}" ]]; then
            echo "ERROR: missing required source file: ${file}" >&2
            exit 1
        fi
    done
}

run_existing_uninstall() {
    if [[ -x "${UNINSTALL_PATH}" ]]; then
        echo "Existing installation detected. Running canonical uninstall first..."
        "${UNINSTALL_PATH}" --force || true
    else
        bash "${SOURCE_DIR}/scripts/uninstall.sh" --force || true
    fi
}

install_docs() {
    mkdir -p "${DOC_DIR}"
    cp "${SOURCE_DIR}/README.md" "${DOC_DIR}/"
    cp "${SOURCE_DIR}/INSTALL.md" "${DOC_DIR}/"
    cp "${SOURCE_DIR}/CHANGELOG.md" "${DOC_DIR}/"
}

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

    require_root
    resolve_source_dir
    validate_source_tree

    echo "=== Installing ${PROJECT_ID} ==="
    run_existing_uninstall

    mkdir -p "${INSTALL_DIR}" "${DOC_DIR}" /usr/local/sbin /etc/default

    install -m 0755 "${SOURCE_DIR}/bin/pve-net-hang-watchdog.sh" "${COMMAND_PATH}"
    install -m 0755 "${SOURCE_DIR}/scripts/uninstall.sh" "${UNINSTALL_PATH}"
    ln -sfn "${UNINSTALL_PATH}" "${UNINSTALL_WRAPPER}"

    if [[ ! -f "${CONFIG_PATH}" ]]; then
        install -m 0644 "${SOURCE_DIR}/config/xdev-pve-net-hang-watchdog" "${CONFIG_PATH}"
    else
        echo "Preserving existing config: ${CONFIG_PATH}"
    fi

    install -m 0644 "${SOURCE_DIR}/systemd/pve-net-hang-watchdog.service" "${UNIT_PATH}"
    systemctl daemon-reload
    systemctl enable --now pve-net-hang-watchdog.service >/dev/null 2>&1

    install_docs

    echo "Installed paths:"
    echo "  command: ${COMMAND_PATH}"
    echo "  uninstall: ${UNINSTALL_PATH}"
    echo "  config: ${CONFIG_PATH}"
    echo "  systemd: ${UNIT_PATH}"
    echo "  docs: ${DOC_DIR}"
    echo "  service: enabled and started"
    echo ""
    echo "Installation completed."
}

main "$@"
