#!/bin/bash
set -e

# SwarmEngine One-Click Installer
# Designed for AlmaLinux 9
# Run via: curl -sL https://GetEngine.SwarmRacks.com | bash

echo "========================================================"
echo "    Installing SwarmEngine Core Architecture"
echo "========================================================"

# 1. System Requirements Check
if [ ! -f /etc/redhat-release ]; then
    echo "Error: SwarmEngine currently requires AlmaLinux 9 or RHEL 9 compatible OS."
    exit 1
fi

echo "[1/7] Installing System Dependencies (KVM, Node.js, Caddy, Build Tools)..."
dnf install -y epel-release dnf-plugins-core
dnf copr enable -y @caddy/caddy
curl -fsSL https://rpm.nodesource.com/setup_20.x | bash -

dnf groupinstall -y "Development Tools"
dnf install -y nodejs caddy gcc make cmake libmicrohttpd-devel openssl-devel libvirt libvirt-devel libvirt-daemon-kvm qemu-kvm jansson-devel

echo "[2/7] Opening Firewall Ports (80, 443, 8080)..."
if command -v firewall-cmd &> /dev/null && systemctl is-active --quiet firewalld; then
    firewall-cmd --permanent --add-port=80/tcp || true
    firewall-cmd --permanent --add-port=443/tcp || true
    firewall-cmd --permanent --add-port=8080/tcp || true
    firewall-cmd --reload || true
else
    echo "FirewallD is not running. Skipping firewall config."
fi

echo "[3/7] Installing Global NPM Packages (PM2)..."
npm install -g pm2

# 2. Directory Structure Setup
echo "[3/7] Setting up /opt/SwarmEngine directory structure..."
mkdir -p /opt/SwarmEngine

if [ -d "./daemon" ] && [ -d "./dashboard" ]; then
    if [ "$(realpath .)" != "/opt/SwarmEngine" ]; then
        echo "Detected local SwarmEngine source code. Copying to /opt/SwarmEngine..."
        cp -r ./daemon /opt/SwarmEngine/
        cp -r ./dashboard /opt/SwarmEngine/
    else
        echo "Running directly from /opt/SwarmEngine. Skipping copy."
    fi
else
    echo "Please ensure the SwarmEngine source code is placed in /opt/SwarmEngine"
    # git clone https://github.com/YourOrg/SwarmEngine.git /opt/SwarmEngine
fi

# 3. Compiling the C Daemon
echo "[4/7] Compiling SwarmD (The Core Daemon)..."
if [ -d "/opt/SwarmEngine/daemon" ]; then
    cd /opt/SwarmEngine/daemon
    make clean && make
fi

# 4. Building the Next.js Dashboard
echo "[5/7] Building the Next.js Setup Wizard & Dashboard..."
if [ -d "/opt/SwarmEngine/dashboard" ]; then
    cd /opt/SwarmEngine/dashboard
    npm install
    npm run build
    pm2 start npm --name "swarm-dashboard" -- run start
    pm2 save
    pm2 startup systemd -u root --hp /root
fi

# 5. Setting up Isolated Caddy Configuration
echo "[6/7] Configuring Isolated Caddy Web Server..."
mkdir -p /etc/swarmengine
cat << 'EOF' > /etc/swarmengine/Caddyfile
# SwarmEngine Initial Setup Wizard Configuration
:8080 {
    # Proxy API requests to the C Daemon
    handle /api/v1/* {
        reverse_proxy 127.0.0.1:8081
    }

    # Proxy everything else to the Next.js Setup Wizard
    handle {
        reverse_proxy 127.0.0.1:3000
    }
}
EOF

# Create a systemd service for the isolated Caddy instance
cat << 'EOF' > /etc/systemd/system/swarmengine-caddy.service
[Unit]
Description=SwarmEngine Caddy Web Server
After=network.target

[Service]
ExecStart=/usr/bin/caddy run --environ --config /etc/swarmengine/Caddyfile
ExecReload=/usr/bin/caddy reload --config /etc/swarmengine/Caddyfile
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now swarmengine-caddy

# 6. Setting up SwarmD systemd service
echo "[7/7] Starting SwarmD Core Service..."
cat << 'EOF' > /etc/systemd/system/swarmd.service
[Unit]
Description=SwarmEngine API Daemon
After=network.target libvirtd.service
Requires=libvirtd.service

[Service]
Type=simple
ExecStart=/opt/SwarmEngine/daemon/swarmd
WorkingDirectory=/opt/SwarmEngine/daemon
Restart=on-failure
RestartSec=5
User=root

[Install]
WantedBy=multi-user.target
EOF

systemctl enable --now libvirtd
systemctl enable --now swarmd

SERVER_IP=$(curl -s ifconfig.me || echo "<your-server-ip>")

echo "========================================================"
echo "    SwarmEngine Installation Complete!"
echo "========================================================"
echo "Please open your browser and navigate to the Setup Wizard:"
echo ""
echo "    http://$SERVER_IP:8080"
echo ""
echo "You will need your SwarmRacks License Key to proceed."
echo "========================================================"
