#!/bin/bash
# ═══════════════════════════════════════════════════════════════════════════════
# VXN ENTERPRISE AGENT - macOS Installer v1.0
# ═══════════════════════════════════════════════════════════════════════════════
#
# One-line install: curl -fsSL https://vellunox.com/downloads/vxn-agent-mac.sh | sudo bash
#
# Features:
# - Installs Splashtop for remote support
# - Configures connection to relay.vellunox.com
# - Registers device with Vellunox RMM
# - Sets up LaunchDaemon 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="/Library/Application Support/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 - macOS 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"

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

# Generate device ID
echo -e "${BLUE}[2/5]${NC} Generating device configuration..."
HOSTNAME=$(hostname -s)
UUID=$(uuidgen | tr '[:upper:]' '[:lower:]' | cut -c1-8)
DEVICE_ID="VXN-${HOSTNAME}-${UUID}"

# Get system info
OS_VERSION=$(sw_vers -productVersion)
HARDWARE=$(sysctl -n hw.model 2>/dev/null || echo "Unknown")

# 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": "macOS",
  "osVersion": "$OS_VERSION",
  "hardware": "$HARDWARE",
  "features": {
    "lucasAI": true,
    "maxGuardian": true,
    "Splashtop": true,
    "autoUpdate": true
  }
}
EOF

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

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

# Check architecture
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ]; then
    Splashtop_URL="https://github.com/Splashtop/Splashtop/releases/download/1.3.7/Splashtop-1.3.7-aarch64.dmg"
else
    Splashtop_URL="https://github.com/Splashtop/Splashtop/releases/download/1.3.7/Splashtop-1.3.7-x86_64.dmg"
fi

# Download Splashtop if not already installed
if [ ! -d "/Applications/Splashtop.app" ]; then
    echo "Downloading Splashtop..."
    DMG_PATH="/tmp/Splashtop.dmg"
    curl -fsSL -o "$DMG_PATH" "$Splashtop_URL"
    
    echo "Mounting DMG..."
    MOUNT_POINT=$(hdiutil attach "$DMG_PATH" -nobrowse -noverify | grep "/Volumes" | awk -F'\t' '{print $NF}')
    
    echo "Installing Splashtop..."
    cp -R "$MOUNT_POINT/Splashtop.app" "/Applications/"
    
    echo "Unmounting..."
    hdiutil detach "$MOUNT_POINT" -quiet
    rm -f "$DMG_PATH"
    
    echo -e "${GREEN}[OK]${NC} Splashtop installed"
else
    echo -e "${YELLOW}[OK]${NC} Splashtop already installed"
fi

# Configure Splashtop for Vellunox relay
Splashtop_CONFIG_DIR="$HOME/.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

echo -e "${GREEN}[OK]${NC} Splashtop configured for ${Splashtop_RELAY}"

# Get Splashtop ID
Splashtop_ID=""
if [ -d "/Applications/Splashtop.app" ]; then
    # Start Splashtop briefly to generate ID
    open -a Splashtop --hide 2>/dev/null || true
    sleep 3
    
    # Try to get the ID from config
    if [ -f "$Splashtop_CONFIG_DIR/Splashtop.toml" ]; then
        Splashtop_ID=$(grep "^id = " "$Splashtop_CONFIG_DIR/Splashtop.toml" 2>/dev/null | cut -d'"' -f2 || echo "")
    fi
fi

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

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

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

send_heartbeat() {
    DEVICE_ID=$(cat "$CONFIG_PATH" | grep deviceId | cut -d'"' -f4)
    HOSTNAME=$(hostname -s)
    
    curl -sf -X POST "$SERVER_URL/api/vxn/heartbeat" \
        -H "Content-Type: application/json" \
        -d "{
            \"deviceId\": \"$DEVICE_ID\",
            \"hostname\": \"$HOSTNAME\",
            \"platform\": \"macOS\",
            \"timestamp\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\"
        }" > /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 LaunchDaemon for auto-start
PLIST_PATH="/Library/LaunchDaemons/com.vellunox.agent.plist"

cat > "$PLIST_PATH" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.vellunox.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>/Library/Application Support/Vellunox/vxn-agent.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Library/Application Support/Vellunox/logs/stdout.log</string>
    <key>StandardErrorPath</key>
    <string>/Library/Application Support/Vellunox/logs/stderr.log</string>
</dict>
</plist>
EOF

# Load the LaunchDaemon
launchctl unload "$PLIST_PATH" 2>/dev/null || true
launchctl load "$PLIST_PATH"

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

# Register with server
echo -e "${BLUE}[5/5]${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\": \"macOS\",
        \"osVersion\": \"$OS_VERSION\",
        \"hardware\": \"$HARDWARE\",
        \"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"
if [ -n "$Splashtop_ID" ]; then
    echo -e "   Splashtop ID:  ${CYAN}$Splashtop_ID${NC}"
fi
echo ""
echo -e "   Your Mac 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
