#!/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. Sets up the Cloudsmith package repository
#   2. Installs ethernull-agent via apt/yum
#   3. Writes enrollment config to /etc/ethernull/
#   4. Starts the agent (connects to gateway)
#
# Requirements: Linux x86_64/arm64, systemd, root

set -euo pipefail

INSTALL_DIR="/opt/ethernull"
CONFIG_DIR="/etc/ethernull"
LOG_DIR="/var/log/ethernull"
SERVICE_NAME="ethernull-agent"

CLOUDSMITH_ORG="ethernullx-labs"
CLOUDSMITH_REPO="ethernullx"
CLOUDSMITH_TOKEN="YVxLkRQcc3VaDx4E"

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"
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 ""

# ─── Detect package manager and set up Cloudsmith repo ─
setup_apt() {
    info "setting up apt repository..."
    apt-get update -qq
    apt-get install -y -qq apt-transport-https gnupg curl >/dev/null 2>&1

    curl -1sLf "https://dl.cloudsmith.io/${CLOUDSMITH_TOKEN}/${CLOUDSMITH_ORG}/${CLOUDSMITH_REPO}/cfg/setup/bash.deb.sh" | bash
    ok "apt repository configured"
}

setup_yum() {
    info "setting up yum repository..."
    curl -1sLf "https://dl.cloudsmith.io/${CLOUDSMITH_TOKEN}/${CLOUDSMITH_ORG}/${CLOUDSMITH_REPO}/cfg/setup/bash.rpm.sh" | bash
    ok "yum repository configured"
}

if command -v apt-get >/dev/null 2>&1; then
    PKG_MGR="apt"
    setup_apt
elif command -v yum >/dev/null 2>&1 || command -v dnf >/dev/null 2>&1; then
    PKG_MGR="yum"
    setup_yum
else
    err "unsupported package manager — need apt or yum/dnf"
fi

# ─── Install package ──────────────────────────────────
info "installing ethernull-agent..."
case "$PKG_MGR" in
    apt) apt-get install -y -qq ethernull-agent >/dev/null 2>&1 ;;
    yum)
        if command -v dnf >/dev/null 2>&1; then
            dnf install -y ethernull-agent >/dev/null 2>&1
        else
            yum install -y ethernull-agent >/dev/null 2>&1
        fi
        ;;
esac
ok "package installed"

# ─── Write enrollment config ──────────────────────────
mkdir -p "$CONFIG_DIR" "$LOG_DIR"
chmod 700 "$CONFIG_DIR"

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

# ─── 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 "upgrade: apt upgrade ethernull-agent  (or yum update ethernull-agent)"
    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
