#!/usr/bin/env bash
# install.sh — Instalador del agente usite-agent
# Uso:
#   curl -sL https://admin.u-site.app/agent/install.sh | bash -s -- --token=TU_TOKEN --url=https://admin.u-site.app
#   o descargando primero:
#   bash install.sh --token=TU_TOKEN --url=https://admin.u-site.app [--interval=30] [--dir=/opt/usite-agent]

set -euo pipefail

# ── Colores ───────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
info()    { echo -e "${BLUE}[INFO]${NC}  $*"; }
ok()      { echo -e "${GREEN}[OK]${NC}    $*"; }
warn()    { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error()   { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }

# ── Parámetros ────────────────────────────────────────────────────────────────
TOKEN=""
API_URL=""
INTERVAL=30
INSTALL_DIR="/opt/usite-agent"

for arg in "$@"; do
  case $arg in
    --token=*)    TOKEN="${arg#*=}" ;;
    --url=*)      API_URL="${arg#*=}" ;;
    --interval=*) INTERVAL="${arg#*=}" ;;
    --dir=*)      INSTALL_DIR="${arg#*=}" ;;
  esac
done

[[ -z "$TOKEN" ]]   && error "Falta --token=TU_TOKEN"
[[ -z "$API_URL" ]] && error "Falta --url=https://admin.u-site.app"

# ── Detectar arquitectura ─────────────────────────────────────────────────────
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case $ARCH in
  x86_64)  ARCH="amd64" ;;
  aarch64) ARCH="arm64" ;;
  armv7l)  ARCH="arm" ;;
  *)       error "Arquitectura no soportada: $ARCH" ;;
esac

BINARY_NAME="usite-agent-${OS}-${ARCH}"
DOWNLOAD_URL="${API_URL}/agent/download/${BINARY_NAME}"

info "Sistema: ${OS}/${ARCH}"
info "Directorio de instalación: ${INSTALL_DIR}"
info "Intervalo de reporte: ${INTERVAL}s"

# ── Crear directorio ──────────────────────────────────────────────────────────
mkdir -p "$INSTALL_DIR"

# ── Descargar binario ─────────────────────────────────────────────────────────
info "Descargando agente desde ${DOWNLOAD_URL}..."
if command -v curl &>/dev/null; then
  curl -fsSL "$DOWNLOAD_URL" -o "${INSTALL_DIR}/usite-agent" || error "No se pudo descargar el binario"
elif command -v wget &>/dev/null; then
  wget -q "$DOWNLOAD_URL" -O "${INSTALL_DIR}/usite-agent" || error "No se pudo descargar el binario"
else
  error "Se requiere curl o wget para descargar el agente"
fi
chmod +x "${INSTALL_DIR}/usite-agent"
ok "Binario descargado y listo"

# ── Crear configuración ───────────────────────────────────────────────────────
cat > "${INSTALL_DIR}/agent.yml" <<EOF
api_url: ${API_URL}
token: ${TOKEN}
interval: ${INTERVAL}
debug: false
EOF
ok "Configuración creada en ${INSTALL_DIR}/agent.yml"

# ── Crear servicio systemd ────────────────────────────────────────────────────
if command -v systemctl &>/dev/null; then
  cat > /etc/systemd/system/usite-agent.service <<EOF
[Unit]
Description=u-site Server Monitoring Agent
After=network.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=${INSTALL_DIR}/usite-agent --config=${INSTALL_DIR}/agent.yml
WorkingDirectory=${INSTALL_DIR}
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=usite-agent

[Install]
WantedBy=multi-user.target
EOF

  systemctl daemon-reload
  systemctl enable usite-agent
  systemctl start usite-agent
  ok "Servicio systemd 'usite-agent' instalado y activo"
  info "Comandos útiles:"
  info "  Ver estado:  systemctl status usite-agent"
  info "  Ver logs:    journalctl -u usite-agent -f"
  info "  Detener:     systemctl stop usite-agent"
  info "  Desinstalar: systemctl disable usite-agent && rm /etc/systemd/system/usite-agent.service"
else
  warn "systemd no disponible. Ejecuta manualmente:"
  warn "  ${INSTALL_DIR}/usite-agent --config=${INSTALL_DIR}/agent.yml &"
fi

echo ""
ok "✅ usite-agent instalado correctamente"
info "El agente empezará a reportar métricas a ${API_URL} cada ${INTERVAL} segundos."
