#!/bin/bash

set -euo pipefail

PROJECT_ID="thunderbolts"
ORG_ID="xdev"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODE="install"
REMOTE_USER="root"
LOCAL_MODE=0
TARGETS=()

get_mgmt_ip() {
    case "$1" in
        baobab) echo "192.168.2.91" ;;
        ebony) echo "192.168.2.92" ;;
        tapia) echo "192.168.2.93" ;;
        *) echo "" ;;
    esac
}

resolve_target() {
    local host="$1"
    local ip=""

    if [[ "$host" == *@* ]]; then
        echo "$host"
        return 0
    fi

    ip="$(get_mgmt_ip "$host")"
    if [[ -n "$ip" ]]; then
        echo "${REMOTE_USER}@${ip}"
    else
        echo "${REMOTE_USER}@${host}"
    fi
}

show_help() {
    cat <<EOF
${PROJECT_ID} setup wrapper

Usage: $0 [OPTIONS] [host...]

Options:
  -h, --help           Show this help message
  -l, --local          Run on localhost
  -u, --uninstall      Uninstall instead of install
  --user <user>        Remote SSH user (default: root)

Without explicit hosts, remote mode defaults to: baobab ebony tapia
EOF
}

run_local_install() {
    bash "${SCRIPT_DIR}/scripts/install.sh" --source-dir "${SCRIPT_DIR}"
}

run_local_uninstall() {
    local canonical="/usr/local/lib/${ORG_ID}/${PROJECT_ID}/uninstall.sh"
    if [[ -x "${canonical}" ]]; then
        "${canonical}"
    else
        bash "${SCRIPT_DIR}/scripts/uninstall.sh"
    fi
}

copy_remote_tree() {
    local target="$1"
    local remote_tmp="$2"

    ssh "${target}" "rm -rf '${remote_tmp}' && mkdir -p '${remote_tmp}/scripts' '${remote_tmp}/deploy/attempt1/common/sbin' '${remote_tmp}/deploy/attempt1/common/systemd/system' '${remote_tmp}/deploy/attempt1/common/udev/rules.d'"
    scp -q "${SCRIPT_DIR}/scripts/install.sh" "${target}:${remote_tmp}/scripts/"
    scp -q "${SCRIPT_DIR}/scripts/uninstall.sh" "${target}:${remote_tmp}/scripts/"
    scp -q "${SCRIPT_DIR}/README.md" "${target}:${remote_tmp}/"
    scp -q "${SCRIPT_DIR}/INSTALL.md" "${target}:${remote_tmp}/"
    scp -q "${SCRIPT_DIR}/CHANGELOG.md" "${target}:${remote_tmp}/"
    scp -q "${SCRIPT_DIR}/deploy/attempt1/common/sbin/tb-recover.sh" "${target}:${remote_tmp}/deploy/attempt1/common/sbin/"
    scp -q "${SCRIPT_DIR}/deploy/attempt1/common/systemd/system/tb-bridge.service" "${target}:${remote_tmp}/deploy/attempt1/common/systemd/system/"
    scp -q "${SCRIPT_DIR}/deploy/attempt1/common/systemd/system/tb-enlist@.service" "${target}:${remote_tmp}/deploy/attempt1/common/systemd/system/"
    scp -q "${SCRIPT_DIR}/deploy/attempt1/common/systemd/system/tb-recover.service" "${target}:${remote_tmp}/deploy/attempt1/common/systemd/system/"
    scp -q "${SCRIPT_DIR}/deploy/attempt1/common/systemd/system/tb-recover.timer" "${target}:${remote_tmp}/deploy/attempt1/common/systemd/system/"
    scp -q "${SCRIPT_DIR}/deploy/attempt1/common/udev/rules.d/90-thunderbolt-net-systemd.rules" "${target}:${remote_tmp}/deploy/attempt1/common/udev/rules.d/"
}

run_remote_install() {
    local target="$1"
    local remote_tmp="/tmp/${PROJECT_ID}.$$"
    local remote_prefix=""

    [[ "${REMOTE_USER}" != "root" ]] && remote_prefix="sudo "

    copy_remote_tree "${target}" "${remote_tmp}"
    ssh "${target}" "${remote_prefix}bash '${remote_tmp}/scripts/install.sh' --source-dir '${remote_tmp}'"
    ssh "${target}" "rm -rf '${remote_tmp}'"
}

run_remote_uninstall() {
    local target="$1"
    local remote_tmp="/tmp/${PROJECT_ID}-uninstall.$$"
    local canonical="/usr/local/lib/${ORG_ID}/${PROJECT_ID}/uninstall.sh"

    ssh "${target}" "rm -rf '${remote_tmp}' && mkdir -p '${remote_tmp}/scripts'"
    scp -q "${SCRIPT_DIR}/scripts/uninstall.sh" "${target}:${remote_tmp}/scripts/"
    if [[ "${REMOTE_USER}" == "root" ]]; then
        ssh "${target}" "if [ -x '${canonical}' ]; then '${canonical}'; else bash '${remote_tmp}/scripts/uninstall.sh'; fi"
    else
        ssh "${target}" "sudo bash -lc \"if [ -x '${canonical}' ]; then '${canonical}'; else bash '${remote_tmp}/scripts/uninstall.sh'; fi\""
    fi
    ssh "${target}" "rm -rf '${remote_tmp}'"
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help)
            show_help
            exit 0
            ;;
        -l|--local)
            LOCAL_MODE=1
            shift
            ;;
        -u|--uninstall)
            MODE="uninstall"
            shift
            ;;
        --user)
            REMOTE_USER="$2"
            shift 2
            ;;
        -*)
            echo "ERROR: unknown option: $1" >&2
            show_help
            exit 1
            ;;
        *)
            TARGETS+=("$1")
            shift
            ;;
    esac
done

if [[ ${#TARGETS[@]} -eq 0 && ${LOCAL_MODE} -eq 0 ]]; then
    TARGETS=(baobab ebony tapia)
fi

echo "================================"
echo "${PROJECT_ID} - ${MODE}"
echo "================================"

if [[ ${LOCAL_MODE} -eq 1 ]]; then
    if [[ "${MODE}" == "install" ]]; then
        run_local_install
    else
        run_local_uninstall
    fi
    exit 0
fi

for host in "${TARGETS[@]}"; do
    if [[ "${MODE}" == "install" ]]; then
        run_remote_install "$(resolve_target "${host}")"
    else
        run_remote_uninstall "$(resolve_target "${host}")"
    fi
done
