#!/usr/bin/env bash

# Exit immediately if a command exits with a non-zero status
set -euo pipefail

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# Parse Arguments
UPDATE_MODE=0
for arg in "$@"; do
    if [ "$arg" == "--update" ]; then
        UPDATE_MODE=1
    fi
done

if [ "$UPDATE_MODE" -eq 1 ]; then
    echo -e "${BLUE}====================================================${NC}"
    echo -e "${BLUE}        Running Rubuz Air Update Process            ${NC}"
    echo -e "${BLUE}====================================================${NC}"
else
    echo -e "${BLUE}====================================================${NC}"
    echo -e "${BLUE}        Welcome to the Rubuz Air Installer          ${NC}"
    echo -e "${BLUE}====================================================${NC}"
fi

# 1. Check for root
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}[!] Please run as root (use: sudo ./air.sh)${NC}"
  exit 1
fi

# 2. Check for Systemd
if ! command -v systemctl &> /dev/null; then
    echo -e "${RED}[!] Systemd is required but not found. This script supports modern Linux distros (Ubuntu, Debian, CentOS, etc).${NC}"
    exit 1
fi

# 3. Check and Install Basic Dependencies
if ! command -v curl &> /dev/null; then
    echo -e "${YELLOW}[*] curl is missing. Attempting to install...${NC}"
    if command -v apt-get &> /dev/null; then
        apt-get update -y && apt-get install -y curl
    elif command -v yum &> /dev/null; then
        yum install -y curl
    else
        echo -e "${RED}[!] Could not install curl automatically. Please install curl and run this script again.${NC}"
        exit 1
    fi
fi

# 4. Install Docker if missing (Skip if Update)
if [ "$UPDATE_MODE" -eq 0 ]; then
    if ! command -v docker &> /dev/null; then
        echo -e "${GREEN}[+] Installing Docker...${NC}"
        curl -fsSL https://get.docker.com -o /tmp/get-docker.sh
        sh /tmp/get-docker.sh
        rm -f /tmp/get-docker.sh
        systemctl enable docker
        systemctl start docker
    else
        echo -e "${GREEN}[+] Docker is already installed.${NC}"
    fi
fi

# 5. Detect Architecture
ARCH=$(uname -m)
if [ "$ARCH" = "x86_64" ]; then
    ARCH="amd64"
elif [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
    ARCH="arm64"
else
    echo -e "${RED}[!] Unsupported architecture: $ARCH${NC}"
    exit 1
fi

# 6. Download and Install Rubuz Air
echo -e "${GREEN}[+] Downloading latest Rubuz Air ($ARCH) from Cloudflare...${NC}"

mkdir -p /opt/rubuz/bin

DOWNLOAD_URL="https://downloads.rubuz.com/air/latest/linux-${ARCH}/rubuz-air"
TMP_BIN="/tmp/rubuz-air.tmp"

# Safely download to a temporary file first
if ! curl -fsSL "$DOWNLOAD_URL" -o "$TMP_BIN"; then
    echo -e "${RED}[!] Failed to download binary from $DOWNLOAD_URL. Please check your network or domain settings.${NC}"
    rm -f "$TMP_BIN"
    exit 1
fi

# Prevent corruption by checking if file is empty
if [ ! -s "$TMP_BIN" ]; then
    echo -e "${RED}[!] Downloaded file is empty. Aborting to prevent corruption.${NC}"
    rm -f "$TMP_BIN"
    exit 1
fi

# Stop service and create backup if updating
if [ "$UPDATE_MODE" -eq 1 ]; then
    echo -e "${GREEN}[+] Stopping existing service...${NC}"
    systemctl stop rubuz-air || true
    
    if [ -f "/opt/rubuz/bin/rubuz-air" ]; then
        echo -e "${GREEN}[+] Backing up current version...${NC}"
        mv /opt/rubuz/bin/rubuz-air /opt/rubuz/bin/rubuz-air.bak
    fi
fi

# Move the verified binary into place
mv "$TMP_BIN" /opt/rubuz/bin/rubuz-air
chmod +x /opt/rubuz/bin/rubuz-air

# 7. Setup Service (Skip creation if Update, just restart)
if [ "$UPDATE_MODE" -eq 0 ]; then
    echo -e "${GREEN}[+] Creating systemd service...${NC}"
    cat <<EOF > /etc/systemd/system/rubuz-air.service
[Unit]
Description=Rubuz Air Control Panel
After=network.target docker.service
Requires=docker.service

[Service]
Type=simple
Environment="PORT=3000"
Environment="DATABASE_URL=/opt/rubuz/rubuz.db"
ExecStart=/opt/rubuz/bin/rubuz-air
Restart=always
RestartSec=5
WorkingDirectory=/opt/rubuz

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable --now rubuz-air
    echo -e "${GREEN}[+] Systemd service 'rubuz-air' created and started!${NC}"
else
    echo -e "${GREEN}[+] Restarting systemd service...${NC}"
    systemctl start rubuz-air
    
    # Wait and check if it started successfully to trigger rollback if needed
    sleep 2
    if ! systemctl is-active --quiet rubuz-air; then
        echo -e "${RED}[!] New version failed to start. Initiating rollback...${NC}"
        systemctl stop rubuz-air || true
        if [ -f "/opt/rubuz/bin/rubuz-air.bak" ]; then
            mv /opt/rubuz/bin/rubuz-air.bak /opt/rubuz/bin/rubuz-air
            systemctl start rubuz-air
            echo -e "${YELLOW}[!] Rolled back to previous version to maintain uptime.${NC}"
        else
            echo -e "${RED}[!] No backup found to roll back to. Please check logs: journalctl -u rubuz-air -e${NC}"
        fi
        exit 1
    else
        echo -e "${GREEN}[+] Systemd service 'rubuz-air' updated and restarted successfully!${NC}"
    fi
fi

# 8. Success Message
echo -e "${BLUE}====================================================${NC}"
if [ "$UPDATE_MODE" -eq 1 ]; then
    echo -e "${GREEN}✅ Rubuz Air Updated Successfully!${NC}"
else
    echo -e "${GREEN}✅ Rubuz Air Installed Successfully!${NC}"
    echo -e "Your Control Panel is running in the background via systemd."
    echo -e "Check status: systemctl status rubuz-air"
    echo -e "Rubuz is now bootstrapping Caddy and networks silently...${NC}"
fi
echo -e "${BLUE}====================================================${NC}"
