#!/bin/bash
# CyberNet Glances Agent Setup
# Installs Glances and starts it in web server mode on port 61208
# Requires: Python 3, pip, sudo/root

BOLD='\033[1m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${BOLD}${CYAN}╔══════════════════════════════════════╗${NC}"
echo -e "${BOLD}${CYAN}║   CyberNet Glances Agent Setup       ║${NC}"
echo -e "${BOLD}${CYAN}╚══════════════════════════════════════╝${NC}"

install_pkg() {
  if command -v apt &>/dev/null; then apt update -qq && apt install -y "$@"
  elif command -v yum &>/dev/null; then yum install -y "$@"
  elif command -v apk &>/dev/null; then apk add "$@"
  else echo "ERROR: No package manager found"; exit 1; fi
}

# Check Python + pip
if ! command -v python3 &>/dev/null; then
    echo "Installing Python 3..."
    install_pkg python3 python3-pip
fi
if ! command -v pip3 &>/dev/null && ! python3 -m pip --version &>/dev/null; then
    echo "Installing pip..."
    install_pkg python3-pip
fi

PIP="pip3"
if ! command -v pip3 &>/dev/null; then PIP="python3 -m pip"; fi

# Install Glances + FastAPI (needed for web mode)
echo -e "${GREEN}Installing Glances...${NC}"
$PIP install glances[web] 2>/dev/null || $PIP install glances 2>/dev/null || $PIP install --break-system-packages glances[web]
$PIP install fastapi uvicorn 2>/dev/null || $PIP install --break-system-packages fastapi uvicorn

# Create systemd service if available
if command -v systemctl &>/dev/null; then
    echo -e "${GREEN}Creating systemd service...${NC}"
    cat > /etc/systemd/system/glances.service << 'SVC'
[Unit]
Description=Glances System Monitor (Web Server)
After=network.target

[Service]
Type=simple
ExecStart=python3 -m glances -w --bind 0.0.0.0 -p 61208
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
SVC

    systemctl daemon-reload
    systemctl enable glances
    systemctl restart glances
    echo -e "${GREEN}Glances service started on port 61208${NC}"
else
    # Fallback: start in background
    echo -e "${GREEN}Starting Glances in background (no systemd)...${NC}"
    nohup python3 -m glances -w --bind 0.0.0.0 -p 61208 > /var/log/glances.log 2>&1 &
    echo $! > /var/run/glances.pid
    echo -e "${GREEN}Glances started PID $(cat /var/run/glances.pid)${NC}"
fi

# Firewall
echo -e "${GREEN}Opening port 61208...${NC}"
if command -v ufw &>/dev/null; then
    ufw allow 61208/tcp 2>/dev/null || true
elif command -v firewall-cmd &>/dev/null; then
    firewall-cmd --add-port=61208/tcp --permanent 2>/dev/null || true
    firewall-cmd --reload 2>/dev/null || true
fi

IP=$(hostname -I | awk '{print $1}')
echo ""
echo -e "${BOLD}${GREEN}✓ Glances Agent installed successfully${NC}"
echo -e "  Web UI:     ${CYAN}http://$IP:61208${NC}"
echo -e "  API:        ${CYAN}http://$IP:61208/api/2/all${NC}"
echo -e "  Dashboard:  ${CYAN}http://$IP:61208/#!/dashboard${NC}"
echo ""
echo -e "Configure this host in CyberNet Glances tab with:"
echo -e "  IP: ${CYAN}$IP${NC}"
echo -e "  Port: ${CYAN}61208${NC}"
echo ""
