#!/bin/sh
# WingGate connector one-line installer / uninstaller.
# Served by the hub at /downloads/install-connector.sh with https://winggate.wweir.fun
# substituted for the hub's public origin and 104d24deb2b6af45a9d717d8bbbf6befbc5fd3c9a9fcfadc041426febb5af14b for the hub's
# configured update trust root. POSIX sh (busybox ash compatible).
set -eu

HUB_ORIGIN="https://winggate.wweir.fun"

# Paths are overridable so the script can be exercised in a sandbox (and by
# packaging); production installs use the defaults.
INSTALL_DIR="${WINGGATE_CONNECTOR_INSTALL_DIR:-/usr/local/bin}"
STATE_DIR="${WINGGATE_CONNECTOR_STATE_DIR:-/var/lib/wingconnector}"
LOG_DIR="${WINGGATE_CONNECTOR_LOG_DIR:-/var/log/wingconnector}"
SYSTEMD_DIR="${WINGGATE_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}"
TRUST_ROOT="${WINGGATE_CONNECTOR_TRUST_ROOT:-/etc/winggate/update-keys}"
UPDATE_INBOX="${WINGGATE_CONNECTOR_UPDATE_INBOX:-/var/lib/winggate/update-inbox}"
# Fleet update trust root (64-hex Ed25519 public keys, comma or space
# separated). The hub renders its configured allowlist into the served copy so
# that a plain one-line install leaves the host able to swap published
# artifacts; --update-keys or the env var overrides it for hosts whose trust
# root is managed out of band.
UPDATE_KEYS="${WINGGATE_CONNECTOR_UPDATE_KEYS:-104d24deb2b6af45a9d717d8bbbf6befbc5fd3c9a9fcfadc041426febb5af14b}"
# Whether the trust root came from the operator rather than from the hub-rendered
# default. An explicit value that yields no key is an error, never a silent
# fallback to the host's existing allowlist (that would look like a completed
# rotation while the old trust root stays in place).
UPDATE_KEYS_EXPLICIT=0
if [ -n "${WINGGATE_CONNECTOR_UPDATE_KEYS:-}" ]; then
    UPDATE_KEYS_EXPLICIT=1
fi

UNIT_NAME="winggate-connector"
LEGACY_UPDATER_UNIT="winggate-connector-update"
BINARY_NAME="winggate-connector"
BINARY_PATH="$INSTALL_DIR/$BINARY_NAME"
CONFIG_PATH="$STATE_DIR/connector.toml"

UNINSTALL=0
REINSTALL=0
PURGE=0
REBIND=0
DRY_RUN=0
FORCE=0

usage() {
    cat <<EOF
WingGate connector installer / uninstaller.

  sh install-connector.sh [options]

    (no options)   install or upgrade (idempotent: an existing bound identity is
                   kept; the service is restarted onto the new binary)
    --uninstall    stop, disable and remove this instance's units. Keeps the
                   identity ($CONFIG_PATH), state and logs
    --purge        with --uninstall/--reinstall: also delete state and logs
    --reinstall    uninstall, then install again
    --rebind       run \`init --force\`: the identity written before is retired on
                   the hub once the new one is bound (needs console approval)
    --dry-run      print what would happen and change nothing
    --force        continue when a guard refuses (e.g. the unit is still active)
    --update-keys <64-hex[,64-hex]>
                   host update trust root written by install-service as root.
                   Defaults to the keys the hub rendered into this script;
                   without it the host gets the updater units but can never
                   swap published artifacts (updaterInstalled stays false)
    --help         print this text

Typical flows:
  install / upgrade              sh install-connector.sh
  service reinstall, same id     sh install-connector.sh --reinstall
  rebind in place                sh install-connector.sh --rebind
  uninstall, keep identity       sh install-connector.sh --uninstall
  fresh machine / full reset     sh install-connector.sh --reinstall --purge
  rebind + unit teardown         sh install-connector.sh --reinstall --rebind
EOF
}

fail() {
    echo "install-connector: error: $*" >&2
    exit 1
}

warn() {
    echo "install-connector: warning: $*" >&2
}

# Keep only 64-hex tokens: an unrendered placeholder, an empty value and a
# malformed override all degrade to "no trust root". install-service validates
# the list again, but the flag must never carry junk, and an empty one would
# make install-service refuse the whole install.
normalize_update_keys() {
    kept=""
    for token in $(printf '%s' "$1" | tr ',' ' '); do
        if [ "${#token}" -ne 64 ]; then
            continue
        fi
        case "$token" in
        *[!0-9a-fA-F]*) continue ;;
        esac
        kept="${kept:+$kept,}$token"
    done
    printf '%s\n' "$kept"
}

# Mutating commands go through run() so --dry-run can print them verbatim.
run() {
    if [ "$DRY_RUN" = 1 ]; then
        echo "[dry-run] $*"
    else
        "$@"
    fi
}

have_systemd() {
    command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]
}

unit_file_present() {
    [ -f "$SYSTEMD_DIR/$1" ]
}

# The per-instance updater unit basename is recorded by `install-service` at
# <state>/update/updater.unit; without the marker the name falls back to the
# legacy pair, exactly like the connector's own resolver does.
updater_unit_basename() {
    name=""
    if [ -f "$STATE_DIR/update/updater.unit" ]; then
        name="$(tr -d ' \t\r\n' <"$STATE_DIR/update/updater.unit" || true)"
    fi
    if [ -n "$name" ]; then
        printf '%s\n' "$name"
    else
        printf '%s\n' "$LEGACY_UPDATER_UNIT"
    fi
}

# A host that also runs the entry connector (or another instance) shares the
# legacy updater unit name. Only remove a pair whose ExecStart pins *this*
# instance: unit name and staging path are rendered per instance by
# `install-service`, so they identify the owner unambiguously.
updater_pair_belongs_here() {
    pair="$1"
    service_file="$SYSTEMD_DIR/$pair.service"
    path_file="$SYSTEMD_DIR/$pair.path"
    if [ ! -f "$service_file" ] && [ ! -f "$path_file" ]; then
        return 1
    fi
    if [ -f "$service_file" ]; then
        if ! grep -qF -- "--unit $UNIT_NAME.service" "$service_file" 2>/dev/null; then
            return 1
        fi
        if ! grep -qF -- "--staging $STATE_DIR/update/" "$service_file" 2>/dev/null; then
            return 1
        fi
    fi
    return 0
}

config_has_identity() {
    if [ -f "$CONFIG_PATH" ] && grep -q 'agentBearerToken' "$CONFIG_PATH" 2>/dev/null; then
        return 0
    fi
    return 1
}

config_agent_id() {
    grep -E '^[[:space:]]*agentId[[:space:]]*=' "$CONFIG_PATH" 2>/dev/null |
        head -n 1 |
        sed -e 's/^[^=]*=[[:space:]]*//' -e 's/"//g' -e "s/'//g" || true
}

purge_state() {
    if [ "$PURGE" != 1 ]; then
        echo "    keeping $CONFIG_PATH and $STATE_DIR (pass --purge to delete them)"
        return 0
    fi
    if config_has_identity; then
        echo "==> Deleting the bound identity and connector state"
        echo "    NOTICE: purging is local. The hub keeps listing this connector as an"
        echo "            offline record; this script cannot retire it without the config."
        agent_id="$(config_agent_id)"
        if [ -n "$agent_id" ]; then
            echo "            agentId: $agent_id"
        fi
        echo "            To retire it automatically use --reinstall --rebind instead;"
        echo "            otherwise revoke it from the console (Connectors -> revoke)."
    fi
    run $SUDO rm -rf "$STATE_DIR" "$LOG_DIR"
}

maybe_remove_binary() {
    if [ "$PURGE" != 1 ]; then
        echo "    keeping $BINARY_PATH (shared by every connector instance on this host)"
        return 0
    fi
    remaining="$(ls "$SYSTEMD_DIR" 2>/dev/null | grep -E '^winggate-.*\.(service|path)$' || true)"
    if [ -n "$remaining" ]; then
        echo "    keeping $BINARY_PATH: other WingGate units remain on this host"
        printf '        %s\n' $remaining
        return 0
    fi
    run $SUDO rm -f "$BINARY_PATH"
}

uninstall_instance() {
    pair="$(updater_unit_basename)"
    pair_owned=0
    if updater_pair_belongs_here "$pair"; then
        pair_owned=1
    fi
    if ! unit_file_present "$UNIT_NAME.service" && [ "$pair_owned" = 0 ]; then
        echo "==> Nothing installed for the '$UNIT_NAME' instance; nothing to remove"
        purge_state
        maybe_remove_binary
        return 0
    fi

    echo "==> Removing the '$UNIT_NAME' service"
    if have_systemd; then
        run $SUDO systemctl disable --now "$UNIT_NAME" || true
        if [ "$DRY_RUN" = 0 ] && systemctl is-active --quiet "$UNIT_NAME"; then
            if [ "$FORCE" = 1 ]; then
                warn "$UNIT_NAME is still active; continuing because --force was given"
            else
                fail "$UNIT_NAME is still active; stop it first (systemctl stop $UNIT_NAME) or pass --force"
            fi
        fi
        # Only ever touch an updater path unit this instance owns: the entry
        # connector shares the legacy unit name, and disabling it would stop
        # the entry's self-update channel silently.
        if [ "$pair_owned" = 1 ]; then
            run $SUDO systemctl disable --now "$pair.path" || true
        fi
    else
        echo "    systemd not detected; handling unit files and state only"
    fi

    run $SUDO rm -f "$SYSTEMD_DIR/$UNIT_NAME.service"
    if [ "$pair_owned" = 1 ]; then
        run $SUDO rm -f "$SYSTEMD_DIR/$pair.path" "$SYSTEMD_DIR/$pair.service"
    else
        echo "    leaving $pair.path/.service in place: they belong to another instance"
        echo "        (the entry connector and a default-named asset instance share that unit name)"
    fi
    if have_systemd; then
        run $SUDO systemctl daemon-reload
        run $SUDO systemctl reset-failed "$UNIT_NAME" || true
    fi

    echo "    keeping host-level state: $TRUST_ROOT and $UPDATE_INBOX"
    echo "        (shared by every WingGate instance on this host)"
    purge_state
    maybe_remove_binary
}

# ---------------------------------------------------------------------------
# Arguments
# ---------------------------------------------------------------------------
while [ $# -gt 0 ]; do
    case "$1" in
    -u | --uninstall) UNINSTALL=1 ;;
    -r | --reinstall)
        UNINSTALL=1
        REINSTALL=1
        ;;
    --purge) PURGE=1 ;;
    --rebind) REBIND=1 ;;
    -n | --dry-run) DRY_RUN=1 ;;
    --force) FORCE=1 ;;
    --update-keys)
        shift
        [ $# -gt 0 ] || fail "--update-keys requires a 64-hex Ed25519 public key value"
        UPDATE_KEYS="$1"
        UPDATE_KEYS_EXPLICIT=1
        ;;
    -h | --help)
        usage
        exit 0
        ;;
    *) fail "unknown option: $1 (see --help)" ;;
    esac
    shift
done

if [ "$PURGE" = 1 ] && [ "$UNINSTALL" = 0 ]; then
    fail "--purge only means something with --uninstall or --reinstall"
fi
if [ "$PURGE" = 1 ] && [ "$REBIND" = 1 ]; then
    fail "--purge deletes the identity that a rebind has to retire; use --reinstall --rebind, or purge and revoke in the console"
fi
# --rebind is not tied to --reinstall: it only changes the install step, and
# rebinding in place (no unit teardown) is the shorter path. State that instead
# of warning about a restriction the script does not enforce.
if [ "$REBIND" = 1 ] && [ "$REINSTALL" = 0 ]; then
    echo "==> Rebinding in place; add --reinstall to tear the units down and reinstall them first"
fi
# Normalize once, before anything mutates the host: install-service validates
# the list again, but a value that reaches it empty would abort the whole
# install, and a bad explicit value must fail loudly rather than fall back to
# whatever trust root the host already has.
UPDATE_KEYS="$(normalize_update_keys "$UPDATE_KEYS")"
if [ "$UPDATE_KEYS_EXPLICIT" = 1 ] && [ -z "$UPDATE_KEYS" ]; then
    fail "--update-keys / WINGGATE_CONNECTOR_UPDATE_KEYS carried no 64-hex Ed25519 key; refusing to continue (drop the value to keep the host's existing trust root)"
fi

# ---------------------------------------------------------------------------
# Privileges
# ---------------------------------------------------------------------------
if [ "$(id -u)" = "0" ]; then
    SUDO=""
elif command -v sudo >/dev/null 2>&1; then
    SUDO="sudo"
else
    fail "root privileges required (run as root or install sudo)"
fi

# ---------------------------------------------------------------------------
# Uninstall
# ---------------------------------------------------------------------------
if [ "$UNINSTALL" = 1 ]; then
    uninstall_instance
    if [ "$REINSTALL" = 0 ]; then
        echo "==> Uninstall complete"
        exit 0
    fi
    echo "==> Reinstalling"
fi

# ---------------------------------------------------------------------------
# Install
# ---------------------------------------------------------------------------
os_name="$(uname -s)"
case "$os_name" in
Linux) OS="linux" ;;
*) fail "unsupported OS: $os_name (the connector is released for Linux only)" ;;
esac

machine="$(uname -m)"
case "$machine" in
x86_64 | amd64) ARCH="x86_64" ;;
aarch64 | arm64) ARCH="aarch64" ;;
*) fail "unsupported CPU architecture: $machine (supported: x86_64, aarch64)" ;;
esac

# The artifact is selected by (os, arch), never by arch alone: aarch64 names
# both Linux arm64 and Apple Silicon and their builds are not interchangeable.
PLATFORM_PATH="$OS/$ARCH"

# Download helper: minimal images often ship only one of curl/wget (busybox
# wget supports -qO).
if command -v curl >/dev/null 2>&1; then
    fetch() { curl -fsSL "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then
    fetch() { wget -qO "$2" "$1"; }
else
    fail "curl or wget is required"
fi

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT INT TERM

echo "==> Downloading $BINARY_NAME ($OS/$ARCH) from $HUB_ORIGIN"
if [ "$DRY_RUN" = 1 ]; then
    echo "[dry-run] fetch $HUB_ORIGIN/downloads/winggate-connector-dist/$PLATFORM_PATH -> $TMP_DIR/connector.tar.gz"
    echo "[dry-run] tar -xzf $TMP_DIR/connector.tar.gz -C $TMP_DIR"
    echo "[dry-run] install -m 0755 $TMP_DIR/$BINARY_NAME $BINARY_PATH"
else
    fetch "$HUB_ORIGIN/downloads/winggate-connector-dist/$PLATFORM_PATH" "$TMP_DIR/connector.tar.gz" ||
        fail "download failed (platform $OS/$ARCH may not be published on this hub)"
    tar -xzf "$TMP_DIR/connector.tar.gz" -C "$TMP_DIR"
    [ -f "$TMP_DIR/$BINARY_NAME" ] || fail "archive did not contain $BINARY_NAME"

    echo "==> Installing $BINARY_PATH"
    $SUDO install -m 0755 "$TMP_DIR/$BINARY_NAME" "$BINARY_PATH"
fi

# Idempotent reinstall: keep an already-bound identity instead of failing on
# `init`. Rebinding stays an explicit opt-in (--rebind / `init --force`).
SKIP_INIT=0
if [ "$REBIND" = 0 ] && config_has_identity; then
    SKIP_INIT=1
    echo "==> Found existing bound connector identity at $CONFIG_PATH; keeping it"
    echo "    To rebind, run this installer with --rebind (or: $BINARY_PATH init --force --config $CONFIG_PATH)"
fi

if [ "$SKIP_INIT" = 0 ]; then
    if [ "$REBIND" = 1 ]; then
        echo "==> Rebinding: the previous identity is retired once the new one is bound"
        echo "    Approve the binding code below in the WingGate console when prompted."
        run $SUDO "$BINARY_PATH" init --force --config "$CONFIG_PATH" --hub "$HUB_ORIGIN"
    else
        echo "==> Initializing connector (writes $CONFIG_PATH)"
        echo "    Approve the binding code below in the WingGate console when prompted."
        run $SUDO "$BINARY_PATH" init --config "$CONFIG_PATH" --hub "$HUB_ORIGIN"
    fi
fi

if have_systemd; then
    echo "==> Installing systemd service"
    update_keys="$UPDATE_KEYS"
    if [ -n "$update_keys" ]; then
        run $SUDO "$BINARY_PATH" install-service --config "$CONFIG_PATH" --force --update-keys "$update_keys"
    else
        run $SUDO "$BINARY_PATH" install-service --config "$CONFIG_PATH" --force
        # Without --update-keys install-service only probes: it never removes an
        # allowlist an earlier install or the deploy pipeline wrote. Warn about
        # a missing trust root only when the host really has none, so a
        # reinstall on an already-converged host does not claim a failure that
        # is not there.
        if [ -s "$TRUST_ROOT" ]; then
            echo "==> Keeping the existing host update trust root: $TRUST_ROOT"
        else
            warn "no update trust root: $TRUST_ROOT is missing and none was supplied, so this host installs the updater units but can never swap published connector artifacts (updaterInstalled stays false)"
            warn "  write it as root: $BINARY_PATH install-service --config $CONFIG_PATH --force --update-keys <64-hex[,64-hex]>"
            warn "  (this hub rendered none into the served script; pass --update-keys or WINGGATE_CONNECTOR_UPDATE_KEYS to supply it)"
        fi
    fi
    if [ "$DRY_RUN" = 0 ]; then
        $SUDO systemctl status "$UNIT_NAME" --no-pager || true
    fi
else
    echo "==> systemd not detected; skipping service installation"
    echo "    Run manually: $BINARY_PATH run --config $CONFIG_PATH"
    echo "    Or wire $BINARY_NAME into your init system (openrc, supervisord, container entrypoint)."
fi

echo "==> Done"
