#!/bin/bash
# Ethernull Agent — SaaS Install Script
#
# Usage:
#   curl -sSL https://releases.ethernullx.com/install.sh | sudo bash -s -- --token <etk_xxx> --gateway wss://gateway.ethernullx.com:9000
#
# What this does:
#   1. Downloads the pre-built agent binary
#   2. Writes config to /etc/ethernull/
#   3. Creates a systemd service
#   4. Starts the agent (connects to gateway)
#
# Requirements: Linux x86_64, systemd, root

set -euo pipefail

BINARY_URL="https://releases.ethernullx.com/agent/latest/ethernull-agent-linux-amd64"
INSTALL_DIR="/opt/ethernull"
CONFIG_DIR="/etc/ethernull"
LOG_DIR="/var/log/ethernull"
SERVICE_NAME="ethernull-agent"

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
BOLD='\033[1m'
RESET='\033[0m'

info()  { echo -e "${CYAN}[ethernull]${RESET} $1"; }
ok()    { echo -e "${GREEN}  ✓${RESET} $1"; }
err()   { echo -e "${RED}  ✗${RESET} $1" >&2; exit 1; }

# ─── Parse args ────────────────────────────────────────
TOKEN=""
GATEWAY=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --token)  TOKEN="$2"; shift 2 ;;
        --gateway) GATEWAY="$2"; shift 2 ;;
        *) err "unknown arg: $1" ;;
    esac
done

[[ -z "$TOKEN" ]] && err "--token is required"
[[ -z "$GATEWAY" ]] && err "--gateway is required"

# Ensure gateway URL includes /ws/agent path
[[ "$GATEWAY" != */ws/agent ]] && GATEWAY="${GATEWAY%/}/ws/agent"

# ─── Preflight ─────────────────────────────────────────
[[ $EUID -ne 0 ]] && err "must run as root (use sudo)"
[[ "$(uname -s)" != "Linux" ]] && err "linux only"

ARCH=$(uname -m)
case "$ARCH" in
    x86_64)  ARCH_SUFFIX="amd64" ;;
    aarch64) ARCH_SUFFIX="arm64" ;;
    *) err "unsupported architecture: $ARCH" ;;
esac

BINARY_URL="https://releases.ethernullx.com/agent/latest/ethernull-agent-linux-${ARCH_SUFFIX}"

command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1 || err "curl or wget required"
command -v systemctl >/dev/null 2>&1 || err "systemd required"

echo -e "${BOLD}"
echo "  ███████╗████████╗██╗  ██╗███████╗██████╗ ███╗   ██╗██╗   ██╗██╗     ██╗     "
echo "  ██╔════╝╚══██╔══╝██║  ██║██╔════╝██╔══██╗████╗  ██║██║   ██║██║     ██║     "
echo "  █████╗     ██║   ███████║█████╗  ██████╔╝██╔██╗ ██║██║   ██║██║     ██║     "
echo "  ██╔══╝     ██║   ██╔══██║██╔══╝  ██╔══██╗██║╚██╗██║██║   ██║██║     ██║     "
echo "  ███████╗   ██║   ██║  ██║███████╗██║  ██║██║ ╚████║╚██████╔╝███████╗███████╗"
echo "  ╚══════╝   ╚═╝   ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚══════╝╚══════╝"
echo -e "${RESET}"
echo ""
info "installing agent..."
echo ""

# ─── Create directories ────────────────────────────────
mkdir -p "$INSTALL_DIR" "$CONFIG_DIR" "$LOG_DIR"
chmod 700 "$CONFIG_DIR"

# ─── Download binary ───────────────────────────────────
info "downloading agent binary (${ARCH_SUFFIX})..."
if command -v curl >/dev/null 2>&1; then
    curl -sSL -o "${INSTALL_DIR}/ethernull-agent" "$BINARY_URL"
else
    wget -qO "${INSTALL_DIR}/ethernull-agent" "$BINARY_URL"
fi
chmod 755 "${INSTALL_DIR}/ethernull-agent"
ok "binary installed"

# ─── Write config ──────────────────────────────────────
cat > "${CONFIG_DIR}/agent.env" <<EOF
ETHERNULL_GATEWAY_URL=${GATEWAY}
ETHERNULL_TOKEN=${TOKEN}
EOF
chmod 600 "${CONFIG_DIR}/agent.env"
ok "config written"

# ─── Create systemd service ────────────────────────────
cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
[Unit]
Description=Ethernull Security Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=${INSTALL_DIR}/ethernull-agent
EnvironmentFile=${CONFIG_DIR}/agent.env
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=ethernull-agent

# Security hardening
NoNewPrivileges=no
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=${LOG_DIR} ${CONFIG_DIR}
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
ok "systemd service created"

# ─── Bundle uninstall script ───────────────────────────
cat > "${INSTALL_DIR}/uninstall.sh" <<'UNINSTALL'
#!/bin/bash
set -euo pipefail
INSTALL_DIR="/opt/ethernull"
CONFIG_DIR="/etc/ethernull"
LOG_DIR="/var/log/ethernull"
SERVICE_NAME="ethernull-agent"
RED='\033[0;31m'; GREEN='\033[0;32m'; CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'
info()  { echo -e "${CYAN}[ethernull]${RESET} $1"; }
ok()    { echo -e "${GREEN}  ✓${RESET} $1"; }
[[ $EUID -ne 0 ]] && { echo "must run as root (use sudo)"; exit 1; }
echo -e "${BOLD}${RED}  Ethernull Agent — Uninstall${RESET}\n"
systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null && { systemctl stop "$SERVICE_NAME"; ok "agent stopped"; }
systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null && { systemctl disable "$SERVICE_NAME" --quiet; ok "service disabled"; }
[[ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]] && { rm -f "/etc/systemd/system/${SERVICE_NAME}.service"; systemctl daemon-reload; ok "systemd unit removed"; }
[[ -d "$CONFIG_DIR" ]] && { rm -rf "$CONFIG_DIR"; ok "removed $CONFIG_DIR"; }
[[ -d "$LOG_DIR" ]] && { rm -rf "$LOG_DIR"; ok "removed $LOG_DIR"; }
journalctl --rotate --quiet 2>/dev/null || true
journalctl --vacuum-time=1s --unit="$SERVICE_NAME" --quiet 2>/dev/null || true
ok "journal cleaned"
rm -rf "$INSTALL_DIR"
echo -e "\n${GREEN}${BOLD}  Agent uninstalled.${RESET}\n"
UNINSTALL
chmod 755 "${INSTALL_DIR}/uninstall.sh"
ok "uninstall script bundled"

# ─── Start ─────────────────────────────────────────────
systemctl daemon-reload
systemctl enable "$SERVICE_NAME" --quiet
systemctl start "$SERVICE_NAME"
ok "agent started"

# ─── Verify ───────────────────────────────────────────
sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo ""
    ok "agent is running"
    info "gateway: ${GATEWAY}"
    info "logs: journalctl -u ${SERVICE_NAME} -f"
    echo ""
    echo -e "${GREEN}${BOLD}  Agent deployed successfully.${RESET}"
    echo ""
else
    echo ""
    err "agent failed to start — check: journalctl -u ${SERVICE_NAME} -e"
fi
