#!/bin/bash
# Hermes Remote Agent — Linux installer (systemd service)
# Installs the agent as a systemd system service with auto-start and auto-restart.
#
# Usage:
#   curl -sSL https://hermes-remote.vkand.ru/install-agent.sh | sudo bash
#   curl -sSL https://hermes-remote.vkand.ru/install-agent.sh | sudo bash -s -- -id my-linux-pc
#
# Requires: root privileges, systemd, curl

set -euo pipefail

RELAY_URL="wss://hermes-remote.vkand.ru"
DEVICE_ID=""
INSTALL_DIR="/opt/hermes-agent"
SERVICE_NAME="hermes-remote-agent"
BINARY_NAME="hermes-agent"
TAGS=""  # additional -tag flags for the agent binary

# ---------- helpers ----------
red()    { echo -e "\033[31m$*\033[0m"; }
green()  { echo -e "\033[32m$*\033[0m"; }
cyan()   { echo -e "\033[36m$*\033[0m"; }

usage() {
    echo "Usage: $0 [-id DEVICE_ID] [-relay RELAY_URL] [-tag KEY=VALUE]..."
    echo ""
    echo "Options:"
    echo "  -id     Device identifier (default: hostname)"
    echo "  -relay  WebSocket relay URL (default: $RELAY_URL)"
    echo "  -tag    Initial tag as key=value (repeatable, e.g. -tag env=staging)"
    exit 1
}

# ---------- parse args ----------
while [[ $# -gt 0 ]]; do
    case "$1" in
        -id)    DEVICE_ID="$2"; shift 2 ;;
        -relay) RELAY_URL="$2"; shift 2 ;;
        -tag)   TAGS="$TAGS -tag $2"; shift 2 ;;
        -h|--help) usage ;;
        *)      echo "Unknown option: $1"; usage ;;
    esac
done

# ---------- check root ----------
if [ "$EUID" -ne 0 ]; then
    red "Error: This script requires root privileges."
    red "Run: curl -sSL ... | sudo bash"
    exit 1
fi

# ---------- check systemd ----------
if ! command -v systemctl &>/dev/null; then
    red "Error: systemd is required but not found."
    exit 1
fi

# ---------- detect architecture ----------
ARCH=$(uname -m)
case "$ARCH" in
    x86_64)     GOARCH="amd64" ;;
    aarch64)    GOARCH="arm64" ;;
    arm64)      GOARCH="arm64" ;;  # macOS-style uname on some ARM SBCs
    *)
        red "Error: Unsupported architecture: $ARCH"
        red "Supported: x86_64 (amd64), aarch64 (arm64)"
        exit 1
        ;;
esac

# ---------- device ID ----------
if [ -z "$DEVICE_ID" ]; then
    DEVICE_ID="$(hostname)"
    read -r -p "Enter device ID [$DEVICE_ID]: " input
    DEVICE_ID="${input:-$DEVICE_ID}"
fi

DOWNLOAD_URL="https://hermes-remote.vkand.ru/dl/agent-linux-${GOARCH}"
BINARY_PATH="$INSTALL_DIR/$BINARY_NAME"

echo ""
cyan "=== Hermes Remote Agent Installer (systemd) ==="
echo "Device:  $DEVICE_ID"
echo "Relay:   $RELAY_URL"
echo "Arch:    $ARCH → $GOARCH (auto-detected)"
echo "Install: $INSTALL_DIR"
echo "Service: $SERVICE_NAME"
echo ""

# ---------- 1. Create install directory ----------
echo "[1/4] Creating $INSTALL_DIR..."
mkdir -p "$INSTALL_DIR"

# ---------- 2. Stop and remove existing service ----------
echo "[2/4] Removing existing service..."
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
    systemctl stop "$SERVICE_NAME"
    echo "       Stopped existing service."
fi
if [ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]; then
    systemctl disable "$SERVICE_NAME" 2>/dev/null || true
    rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
    systemctl daemon-reload
    echo "       Removed previous unit file."
fi

# ---------- 3. Download agent binary ----------
echo "[3/4] Downloading agent from $DOWNLOAD_URL..."
if command -v curl &>/dev/null; then
    curl -sSL "$DOWNLOAD_URL" -o "$BINARY_PATH"
elif command -v wget &>/dev/null; then
    wget -q "$DOWNLOAD_URL" -O "$BINARY_PATH"
else
    red "Error: neither curl nor wget found. Install one of them first."
    exit 1
fi
chmod +x "$BINARY_PATH"
size=$(stat -c%s "$BINARY_PATH" 2>/dev/null || stat -f%z "$BINARY_PATH" 2>/dev/null || echo "?")
echo "       $size bytes"

# Write persistent config
cat > "$INSTALL_DIR/agent-config.json" << EOF
{
  "device_id": "$DEVICE_ID",
  "relay_url": "$RELAY_URL"
}
EOF
echo "       Config saved: $INSTALL_DIR/agent-config.json"

# ---------- 4. Create and start systemd service ----------
echo "[4/4] Creating systemd service '$SERVICE_NAME'..."

cat > "/etc/systemd/system/${SERVICE_NAME}.service" << SYSTEMDEOF
[Unit]
Description=Hermes Remote Agent ($DEVICE_ID)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=$BINARY_PATH -relay $RELAY_URL -id $DEVICE_ID$TAGS
Restart=always
RestartSec=5
User=root

# Security hardening
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=$INSTALL_DIR
PrivateTmp=yes

[Install]
WantedBy=multi-user.target
SYSTEMDEOF

systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"

sleep 1
STATUS=$(systemctl is-active "$SERVICE_NAME" || echo "unknown")

echo ""
green "Done! Agent installed as systemd service."
echo ""
echo "Service details:"
echo "  Name:        $SERVICE_NAME"
echo "  Binary:      $BINARY_PATH"
echo "  Device ID:   $DEVICE_ID"
echo "  Relay:       $RELAY_URL"
echo "  Status:      $STATUS"
echo "  Start:       Automatic (at boot)"
echo ""
echo "Manual control:"
echo "  systemctl start   $SERVICE_NAME"
echo "  systemctl stop    $SERVICE_NAME"
echo "  systemctl status  $SERVICE_NAME"
echo "  journalctl -u     $SERVICE_NAME -f"
echo ""
echo "To uninstall:"
echo "  sudo systemctl stop $SERVICE_NAME"
echo "  sudo systemctl disable $SERVICE_NAME"
echo "  sudo rm /etc/systemd/system/${SERVICE_NAME}.service"
echo "  sudo systemctl daemon-reload"
echo "  sudo rm -rf $INSTALL_DIR"
echo ""
