#!/usr/bin/env bash
#
# AgentIQ Agent Installer (self-extracting)
#
# Installs agentiq-agent on a managed host.
# Run again to update. Configs are never overwritten.
#

set -euo pipefail

INSTALL_VERSION="v0.0.0-152"
OS="$(uname -s)"

# --- Help ---
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
    echo "AgentIQ Agent Installer ${INSTALL_VERSION}"
    echo
    echo "Usage: bash install-agent.sh [options]"
    echo
    echo "Options:"
    echo "  --system         Install system-wide (root, /usr/local/bin)"
    echo "  --user           Install for current user (~/.local/bin)"
    echo "  --uninstall      Remove AgentIQ agent binary and services"
    echo "  --help           Show this help"
    exit 0
fi

# --- Parse arguments ---
INSTALL_MODE=""
UNINSTALL=false
while [[ $# -gt 0 ]]; do
    case "$1" in
        --system)    INSTALL_MODE="system"; shift ;;
        --user)      INSTALL_MODE="user"; shift ;;
        --uninstall) UNINSTALL=true; shift ;;
        *)           echo "Unknown option: $1 (try --help)"; exit 1 ;;
    esac
done

# --- Detect or prompt for install mode ---
if [[ -z "$INSTALL_MODE" ]]; then
    if [[ -f /usr/local/bin/agentiq-agent ]]; then
        INSTALL_MODE="system"
    elif [[ -f "$HOME/.local/bin/agentiq-agent" ]]; then
        INSTALL_MODE="user"
    else
        echo
        echo "  Install mode:"
        echo "    1. System (recommended) — installs to /usr/local/bin, runs as root"
        echo "    2. User — installs to ~/.local/bin, runs as current user"
        echo
        read -p "  Choose [1]: " MODE_CHOICE < /dev/tty || MODE_CHOICE=""
        MODE_CHOICE="${MODE_CHOICE:-1}"
        case "$MODE_CHOICE" in
            1) INSTALL_MODE="system" ;;
            2) INSTALL_MODE="user" ;;
            *) echo "  Invalid choice"; exit 1 ;;
        esac
    fi
fi

# --- Set paths based on mode ---
if [[ "$INSTALL_MODE" == "system" ]]; then
    BIN_DIR="/usr/local/bin"
    CONFIG_DIR="/etc/agentiq"
else
    BIN_DIR="$HOME/.local/bin"
    CONFIG_DIR="$HOME/.config/agentiq"
fi

# --- Uninstall ---
if [[ "$UNINSTALL" == true ]]; then
    echo "Uninstalling AgentIQ agent..."

    if [[ "$OS" == "Linux" ]] && command -v systemctl &>/dev/null; then
        systemctl stop agentiq-agent 2>/dev/null || true
        systemctl disable agentiq-agent 2>/dev/null || true
        rm -f /etc/systemd/system/agentiq-agent.service
        systemctl daemon-reload 2>/dev/null || true
        echo "  Removed systemd service"
    fi

    if [[ "$OS" == "Darwin" ]]; then
        if [[ -f /Library/LaunchDaemons/dev.agentiq.agent.plist ]]; then
            launchctl unload /Library/LaunchDaemons/dev.agentiq.agent.plist 2>/dev/null || true
            rm -f /Library/LaunchDaemons/dev.agentiq.agent.plist
            echo "  Removed system LaunchDaemon"
        fi
        PLIST="$HOME/Library/LaunchAgents/dev.agentiq.agent.plist"
        if [[ -f "$PLIST" ]]; then
            launchctl unload "$PLIST" 2>/dev/null || true
            rm -f "$PLIST"
            echo "  Removed user LaunchAgent"
        fi
    fi

    for dir in /usr/local/bin "$HOME/.local/bin"; do
        if [[ -f "${dir}/agentiq-agent" ]]; then
            rm -f "${dir}/agentiq-agent"
            echo "  Removed ${dir}/agentiq-agent"
        fi
    done

    echo
    echo "AgentIQ agent uninstalled."
    echo "Config directories were NOT removed."
    exit 0
fi

# --- Check if update is needed ---
INSTALLED="none"
if command -v agentiq-agent &>/dev/null; then
    INSTALLED="$(agentiq-agent --version 2>/dev/null | head -1 || echo "unknown")"
fi

if [[ "$INSTALLED" == *"$INSTALL_VERSION"* ]] && [[ "$INSTALLED" != "none" ]]; then
    echo "AgentIQ Agent ${INSTALL_VERSION} is already installed."
    exit 0
fi

if [[ "$INSTALLED" == "none" ]]; then
    echo "Installing AgentIQ Agent ${INSTALL_VERSION} (${INSTALL_MODE} mode)..."
else
    echo "Updating AgentIQ Agent (${INSTALLED} -> ${INSTALL_VERSION})..."
fi
echo "  Install: ${BIN_DIR}/"
echo

# --- Extract embedded payload ---
TMPDIR="$(mktemp -d)"
trap 'rm -rf "$TMPDIR"' EXIT

ARCHIVE_START=$(awk '/^__ARCHIVE__$/{print NR + 1; exit 0;}' "$0")
tail -n +"${ARCHIVE_START}" "$0" | base64 -d | tar xz -C "${TMPDIR}"

# --- Stop service if running ---
AGENT_WAS_RUNNING=false
if [[ "$OS" == "Linux" ]] && command -v systemctl &>/dev/null; then
    if systemctl is-active --quiet agentiq-agent 2>/dev/null; then
        echo "Stopping agentiq-agent..."
        systemctl stop agentiq-agent
        AGENT_WAS_RUNNING=true
    fi
elif [[ "$OS" == "Darwin" ]]; then
    if launchctl list dev.agentiq.agent &>/dev/null; then
        launchctl unload /Library/LaunchDaemons/dev.agentiq.agent.plist 2>/dev/null || true
        launchctl unload "$HOME/Library/LaunchAgents/dev.agentiq.agent.plist" 2>/dev/null || true
        AGENT_WAS_RUNNING=true
    fi
fi

# --- Install binary ---
mkdir -p "$BIN_DIR"
if [[ -f "${TMPDIR}/agentiq-agent" ]]; then
    cp "${TMPDIR}/agentiq-agent" "${BIN_DIR}/agentiq-agent"
    chmod 0755 "${BIN_DIR}/agentiq-agent"
    echo "  ${BIN_DIR}/agentiq-agent"
else
    echo "Error: agentiq-agent not found in payload"
    exit 1
fi

# --- Install service ---
if [[ "$OS" == "Linux" ]] && command -v systemctl &>/dev/null; then
    if [[ -f "${TMPDIR}/agentiq-agent.service" ]]; then
        cp "${TMPDIR}/agentiq-agent.service" /etc/systemd/system/agentiq-agent.service
        echo "  /etc/systemd/system/agentiq-agent.service"
        systemctl daemon-reload
    fi
elif [[ "$OS" == "Darwin" ]]; then
    if [[ "$INSTALL_MODE" == "system" ]]; then
        if [[ -f "${TMPDIR}/dev.agentiq.agent.system.plist" ]]; then
            cp "${TMPDIR}/dev.agentiq.agent.system.plist" /Library/LaunchDaemons/dev.agentiq.agent.plist
            echo "  /Library/LaunchDaemons/dev.agentiq.agent.plist"
        fi
    else
        if [[ -f "${TMPDIR}/dev.agentiq.agent.plist" ]]; then
            mkdir -p "$HOME/Library/LaunchAgents"
            cp "${TMPDIR}/dev.agentiq.agent.plist" "$HOME/Library/LaunchAgents/"
            echo "  $HOME/Library/LaunchAgents/dev.agentiq.agent.plist"
        fi
    fi
fi

# --- Create directories and generate token ---
mkdir -p "$CONFIG_DIR"
if [[ "$INSTALL_MODE" == "system" ]]; then
    mkdir -p /etc/agentiq/tls
    chmod 0750 /etc/agentiq/tls
fi

GENERATED_TOKEN=""
if [[ "$OS" == "Linux" ]] && [[ "$INSTALL_MODE" == "system" ]]; then
    ENVFILE="/etc/sysconfig/agentiq-agent"
    if [[ ! -f "$ENVFILE" ]]; then
        GENERATED_TOKEN=$(head -c 32 /dev/urandom | base64 | tr -d '/+=' | head -c 32)
        mkdir -p /etc/sysconfig
        echo "# AgentIQ Agent environment — used by systemd unit" > "$ENVFILE"
        echo "AGENTIQ_AGENT_TOKEN=${GENERATED_TOKEN}" >> "$ENVFILE"
        chmod 0600 "$ENVFILE"
    else
        GENERATED_TOKEN=$(grep -oP 'AGENTIQ_AGENT_TOKEN=\K.*' "$ENVFILE" 2>/dev/null || true)
    fi
elif [[ "$OS" == "Darwin" ]]; then
    # On macOS, store token in the agent config file.
    AGENT_CONFIG="${CONFIG_DIR}/agent.yaml"
    if [[ ! -f "$AGENT_CONFIG" ]]; then
        GENERATED_TOKEN=$(head -c 32 /dev/urandom | base64 | tr -d '/+=' | head -c 32)
        cat > "$AGENT_CONFIG" <<YAML
agent:
  token: ${GENERATED_TOKEN}
  listen: ":8443"
YAML
        chmod 0600 "$AGENT_CONFIG"
    else
        GENERATED_TOKEN=$(grep 'token:' "$AGENT_CONFIG" 2>/dev/null | awk '{print $2}' || true)
    fi
fi

# --- Start the service ---
if [[ "$OS" == "Linux" ]] && command -v systemctl &>/dev/null; then
    if [[ "$AGENT_WAS_RUNNING" == true ]]; then
        echo "Restarting agentiq-agent..."
        systemctl restart agentiq-agent
    elif systemctl is-enabled --quiet agentiq-agent 2>/dev/null; then
        echo "Restarting agentiq-agent..."
        systemctl restart agentiq-agent
    else
        echo "Starting agentiq-agent..."
        systemctl enable --now agentiq-agent
    fi
elif [[ "$OS" == "Darwin" ]]; then
    if [[ "$INSTALL_MODE" == "system" ]]; then
        PLIST="/Library/LaunchDaemons/dev.agentiq.agent.plist"
    else
        PLIST="$HOME/Library/LaunchAgents/dev.agentiq.agent.plist"
    fi
    if [[ -f "$PLIST" ]]; then
        echo "Starting agentiq-agent..."
        launchctl load "$PLIST" 2>/dev/null || true
    fi
fi

# --- Done ---
echo
echo "AgentIQ Agent ${INSTALL_VERSION} installed (${INSTALL_MODE} mode)."

if ! command -v agentiq-agent &>/dev/null; then
    echo
    echo "Add ${BIN_DIR} to your PATH:"
    echo "  export PATH=\"${BIN_DIR}:\$PATH\""
fi

# Show the token and TUI instructions.
HOSTNAME=$(hostname -f 2>/dev/null || hostname)

if [[ -n "${GENERATED_TOKEN:-}" ]]; then
    echo
    echo "  Agent token: ${GENERATED_TOKEN}"
    echo
    echo "  To add this host from the AgentIQ TUI:"
    echo "    /host add ${HOSTNAME} agent://${GENERATED_TOKEN}@${HOSTNAME}"
    echo
    echo "  Or from the CLI:"
    echo "    agentiq hosts add ${HOSTNAME} agent://${GENERATED_TOKEN}@${HOSTNAME}"
fi

exit 0
__ARCHIVE__
[payload removed: 5898240 characters]
