#!/bin/bash
# ═══════════════════════════════════════════════════════════════════════════════
# VXN ENTERPRISE AGENT - Linux Installer v1.0
# ═══════════════════════════════════════════════════════════════════════════════
#
# One-line install: curl -fsSL https://vellunox.com/downloads/vxn-agent-linux.sh | sudo bash
#
# Supports: Ubuntu, Debian, CentOS, RHEL, Fedora, Arch Linux
#
# Features:
# - Installs Splashtop for remote support
# - Configures connection to relay.vellunox.com
# - Registers device with Vellunox RMM
# - Sets up systemd service for auto-start
#
# Copyright (c) 2026 Vellunox Technologies LLC
# ═══════════════════════════════════════════════════════════════════════════════

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Configuration
AGENT_VERSION="1.0.0"
INSTALL_PATH="/opt/vellunox"
LOG_PATH="$INSTALL_PATH/logs"
CONFIG_PATH="$INSTALL_PATH/config.json"
SERVER_URL="https://vellunox.com"
Splashtop_RELAY="relay.vellunox.com"
Splashtop_KEY="utvz43l9c3YALmquThEp9CP6NmXzFwcYNYd7cUWHlgc="

echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════════════════════${NC}"
echo -e "${CYAN}   VXN ENTERPRISE AGENT - Linux Installer v${AGENT_VERSION}${NC}"
echo -e "${CYAN}   Complete RMM Protection with Lucas AI${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════════════════════${NC}"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}[ERROR] Please run as root (sudo)${NC}"
    exit 1
fi

echo -e "${GREEN}[OK]${NC} Running as root"

# Detect distribution
detect_distro() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        DISTRO=$ID
        DISTRO_VERSION=$VERSION_ID
    elif [ -f /etc/redhat-release ]; then
        DISTRO="rhel"
    elif [ -f /etc/debian_version ]; then
        DISTRO="debian"
    else
        DISTRO="unknown"
    fi
    echo -e "${GREEN}[OK]${NC} Detected: $DISTRO $DISTRO_VERSION"
}

detect_distro

# Create directories
echo -e "${BLUE}[1/6]${NC} Creating installation directories..."
mkdir -p "$INSTALL_PATH"
mkdir -p "$LOG_PATH"
mkdir -p "$INSTALL_PATH/data"
mkdir -p "$INSTALL_PATH/scripts"
echo -e "${GREEN}[OK]${NC} Directories created at $INSTALL_PATH"

# Generate device ID
echo -e "${BLUE}[2/6]${NC} Generating device configuration..."
HOSTNAME=$(hostname -s)
UUID=$(cat /proc/sys/kernel/random/uuid | cut -c1-8)
DEVICE_ID="VXN-${HOSTNAME}-${UUID}"

# Get system info
OS_VERSION=$(cat /etc/os-release 2>/dev/null | grep PRETTY_NAME | cut -d'"' -f2 || echo "Linux")
ARCH=$(uname -m)
KERNEL=$(uname -r)

# Create config
cat > "$CONFIG_PATH" << EOF
{
  "deviceId": "$DEVICE_ID",
  "hostname": "$HOSTNAME",
  "serverUrl": "$SERVER_URL",
  "installedAt": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "installerVersion": "$AGENT_VERSION",
  "platform": "Linux",
  "distro": "$DISTRO",
  "osVersion": "$OS_VERSION",
  "arch": "$ARCH",
  "kernel": "$KERNEL",
  "features": {
    "lucasAI": true,
    "maxGuardian": true,
    "Splashtop": true,
    "autoUpdate": true
  }
}
EOF

echo -e "${GREEN}[OK]${NC} Device ID: $DEVICE_ID"

# Install dependencies
echo -e "${BLUE}[3/6]${NC} Installing dependencies..."

case $DISTRO in
    ubuntu|debian|pop|linuxmint)
        apt-get update -qq
        apt-get install -y -qq curl wget jq libgtk-3-0 libxcb-randr0 libxdo3 libxfixes3 libxcb-shape0 libxcb-xfixes0 libasound2 libpulse0 2>/dev/null || true
        ;;
    centos|rhel|fedora|rocky|almalinux)
        if command -v dnf &> /dev/null; then
            dnf install -y -q curl wget jq gtk3 libxcb alsa-lib pulseaudio-libs 2>/dev/null || true
        else
            yum install -y -q curl wget jq gtk3 libxcb alsa-lib pulseaudio-libs 2>/dev/null || true
        fi
        ;;
    arch|manjaro)
        pacman -Sy --noconfirm --quiet curl wget jq gtk3 libxcb alsa-lib pulseaudio 2>/dev/null || true
        ;;
    *)
        echo -e "${YELLOW}[WARN]${NC} Unknown distro, skipping dependency install"
        ;;
esac

echo -e "${GREEN}[OK]${NC} Dependencies installed"

# Install Splashtop
echo -e "${BLUE}[4/6]${NC} Installing Splashtop for remote support..."

Splashtop_INSTALLED=false
if ! command -v Splashtop &> /dev/null; then
    # Determine architecture
    case $ARCH in
        x86_64|amd64)
            Splashtop_ARCH="x86_64"
            ;;
        aarch64|arm64)
            Splashtop_ARCH="aarch64"
            ;;
        *)
            echo -e "${YELLOW}[WARN]${NC} Unsupported architecture: $ARCH"
            Splashtop_ARCH=""
            ;;
    esac
    
    if [ -n "$Splashtop_ARCH" ]; then
        case $DISTRO in
            ubuntu|debian|pop|linuxmint)
                Splashtop_URL="https://github.com/Splashtop/Splashtop/releases/download/1.3.7/Splashtop-1.3.7-${Splashtop_ARCH}.deb"
                wget -q -O /tmp/Splashtop.deb "$Splashtop_URL"
                dpkg -i /tmp/Splashtop.deb 2>/dev/null || apt-get install -f -y -qq
                rm -f /tmp/Splashtop.deb
                Splashtop_INSTALLED=true
                ;;
            centos|rhel|fedora|rocky|almalinux)
                Splashtop_URL="https://github.com/Splashtop/Splashtop/releases/download/1.3.7/Splashtop-1.3.7-0.${Splashtop_ARCH}.rpm"
                if command -v dnf &> /dev/null; then
                    dnf install -y "$Splashtop_URL" 2>/dev/null || true
                else
                    yum install -y "$Splashtop_URL" 2>/dev/null || true
                fi
                Splashtop_INSTALLED=true
                ;;
            arch|manjaro)
                # Use AUR or manual install
                echo -e "${YELLOW}[WARN]${NC} Please install Splashtop from AUR manually"
                ;;
            *)
                echo -e "${YELLOW}[WARN]${NC} Splashtop installation not supported for $DISTRO"
                ;;
        esac
    fi
else
    Splashtop_INSTALLED=true
    echo -e "${YELLOW}[OK]${NC} Splashtop already installed"
fi

if [ "$Splashtop_INSTALLED" = true ]; then
    # Configure Splashtop for Vellunox relay
    Splashtop_CONFIG_DIR="/root/.config/Splashtop"
    mkdir -p "$Splashtop_CONFIG_DIR"
    
    cat > "$Splashtop_CONFIG_DIR/Splashtop2.toml" << EOF
rendezvous_server = '${Splashtop_RELAY}'
nat_type = 1
serial = 0

[options]
direct-server = '${Splashtop_RELAY}'
relay-server = '${Splashtop_RELAY}'
key = '${Splashtop_KEY}'
custom-rendezvous-server = '${Splashtop_RELAY}'
EOF
    
    # Also configure for all users
    for USER_HOME in /home/*; do
        if [ -d "$USER_HOME" ]; then
            USER_CONFIG="$USER_HOME/.config/Splashtop"
            mkdir -p "$USER_CONFIG"
            cp "$Splashtop_CONFIG_DIR/Splashtop2.toml" "$USER_CONFIG/"
            chown -R $(basename "$USER_HOME"):$(basename "$USER_HOME") "$USER_CONFIG" 2>/dev/null || true
        fi
    done
    
    echo -e "${GREEN}[OK]${NC} Splashtop configured for ${Splashtop_RELAY}"
    
    # Install Splashtop service
    if command -v Splashtop &> /dev/null; then
        Splashtop --install-service 2>/dev/null || true
        systemctl enable Splashtop 2>/dev/null || true
        systemctl start Splashtop 2>/dev/null || true
    fi
fi

# Get Splashtop ID
Splashtop_ID=""
if command -v Splashtop &> /dev/null; then
    Splashtop_ID=$(Splashtop --get-id 2>/dev/null || echo "")
fi

# Create agent script
echo -e "${BLUE}[5/6]${NC} Creating agent service..."

cat > "$INSTALL_PATH/vxn-agent.sh" << 'AGENTSCRIPT'
#!/bin/bash
# VXN Agent Service Script
CONFIG_PATH="/opt/vellunox/config.json"
LOG_PATH="/opt/vellunox/logs/agent.log"
SERVER_URL="https://vellunox.com"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_PATH"
}

get_system_info() {
    CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1 2>/dev/null || echo "0")
    MEM_TOTAL=$(free -m | awk '/Mem:/ {print $2}')
    MEM_USED=$(free -m | awk '/Mem:/ {print $3}')
    MEM_PERCENT=$((MEM_USED * 100 / MEM_TOTAL))
    DISK_PERCENT=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
    UPTIME=$(cat /proc/uptime | awk '{print int($1)}')
    
    echo "{\"cpu\": $CPU_USAGE, \"memory\": $MEM_PERCENT, \"disk\": $DISK_PERCENT, \"uptime\": $UPTIME}"
}

send_heartbeat() {
    DEVICE_ID=$(cat "$CONFIG_PATH" | grep -o '"deviceId": *"[^"]*"' | cut -d'"' -f4)
    HOSTNAME=$(hostname -s)
    SYSTEM_INFO=$(get_system_info)
    
    curl -sf -X POST "$SERVER_URL/api/vxn/heartbeat" \
        -H "Content-Type: application/json" \
        -d "{
            \"deviceId\": \"$DEVICE_ID\",
            \"hostname\": \"$HOSTNAME\",
            \"platform\": \"Linux\",
            \"timestamp\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\",
            \"metrics\": $SYSTEM_INFO
        }" > /dev/null 2>&1
}

log "VXN Agent started"
send_heartbeat

# Main loop - heartbeat every 5 minutes
while true; do
    sleep 300
    send_heartbeat
done
AGENTSCRIPT

chmod +x "$INSTALL_PATH/vxn-agent.sh"

# Create systemd service
cat > /etc/systemd/system/vxn-agent.service << EOF
[Unit]
Description=VXN Enterprise Agent with Lucas AI
After=network.target

[Service]
Type=simple
ExecStart=/bin/bash /opt/vellunox/vxn-agent.sh
Restart=always
RestartSec=30
StandardOutput=append:/opt/vellunox/logs/stdout.log
StandardError=append:/opt/vellunox/logs/stderr.log

[Install]
WantedBy=multi-user.target
EOF

# Enable and start service
systemctl daemon-reload
systemctl enable vxn-agent
systemctl start vxn-agent

echo -e "${GREEN}[OK]${NC} Agent service installed and started"

# Register with server
echo -e "${BLUE}[6/6]${NC} Registering with Vellunox..."

REG_RESULT=$(curl -sf -X POST "$SERVER_URL/api/vxn/register" \
    -H "Content-Type: application/json" \
    -d "{
        \"hostname\": \"$HOSTNAME\",
        \"deviceId\": \"$DEVICE_ID\",
        \"agentVersion\": \"$AGENT_VERSION\",
        \"platform\": \"Linux\",
        \"distro\": \"$DISTRO\",
        \"osVersion\": \"$OS_VERSION\",
        \"arch\": \"$ARCH\",
        \"kernel\": \"$KERNEL\",
        \"SplashtopId\": \"$Splashtop_ID\",
        \"installedAt\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\"
    }" 2>/dev/null) || echo ""

if [ -n "$REG_RESULT" ]; then
    echo -e "${GREEN}[OK]${NC} Registered with Vellunox"
else
    echo -e "${YELLOW}[WARN]${NC} Registration pending (will retry on heartbeat)"
fi

# Done
echo ""
echo -e "${GREEN}═══════════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}   INSTALLATION COMPLETE!${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════════════════════${NC}"
echo ""
echo -e "   Device ID:    ${CYAN}$DEVICE_ID${NC}"
echo -e "   Install Path: $INSTALL_PATH"
echo -e "   Distro:       $OS_VERSION"
if [ -n "$Splashtop_ID" ]; then
    echo -e "   Splashtop ID:  ${CYAN}$Splashtop_ID${NC}"
fi
echo ""
echo -e "   Service commands:"
echo -e "     systemctl status vxn-agent   # Check status"
echo -e "     journalctl -u vxn-agent -f   # View logs"
echo ""
echo -e "   Your device is now protected by VXN Agent with Lucas AI!"
echo -e "   View your device at: ${CYAN}https://vellunox.com/rmm-dashboard${NC}"
echo ""
echo -e "${GREEN}═══════════════════════════════════════════════════════════════════${NC}"
echo ""

exit 0
