#!/bin/bash
set -e

# Configuration
DOWNLOAD_URL="https://download.onifast.com/latest"
BIN_DIR="/usr/local/bin"
SERVICE_DIR="/etc/systemd/system"
WORKDIR="/home/root/onifast"
LOG_DIR="/var/log/onifast"
TMP_DIR=$(mktemp -d)

# Clean up temp dir on exit
trap 'rm -rf "$TMP_DIR"' EXIT

# Flat list of binaries (served at $DOWNLOAD_URL/<name>)
BINARIES=(
    "onifast-panel"
    "onifast-s3"
    "onifast-relay"
    "onifast-dns"
    "onifast-web"
    "onifast-mail"
    "onifast-ftp"
)

# Systemd service files (served at $DOWNLOAD_URL/<service>)
SERVICES=(
    "onifast-panel.service"
    "onifast-s3.service"
    "onifast-relay.service"
    "onifast-dns.service"
    "onifast-web.service"
    "onifast-mail.service"
    "onifast-ftp.service"
)

echo "--- Phase 1: Downloading New Files ---"

# 1. Download Binaries to Temp
for filename in "${BINARIES[@]}"; do
    echo "Downloading $filename..."
    curl -fsSL "$DOWNLOAD_URL/$filename" -o "$TMP_DIR/$filename" || { echo "Failed to download $filename"; exit 1; }
    chmod +x "$TMP_DIR/$filename"
done

# 2. Download Service Files to Temp
for service in "${SERVICES[@]}"; do
    echo "Downloading $service..."
    curl -fsSL "$DOWNLOAD_URL/$service" -o "$TMP_DIR/$service" || { echo "Failed to download $service"; exit 1; }
done

echo "--- Phase 2: Stopping and Cleaning Old Services ---"

# 3. Stop and remove existing services/binaries
for service in "${SERVICES[@]}"; do
    if systemctl is-active --quiet "$service"; then
        echo "Stopping $service..."
        systemctl stop "$service"
    fi

    if [ -f "$SERVICE_DIR/$service" ]; then
        echo "Removing old service file $service..."
        systemctl disable "$service" --quiet || true
        rm -f "$SERVICE_DIR/$service"
    fi
done

for filename in "${BINARIES[@]}"; do
    if [ -f "$BIN_DIR/$filename" ]; then
        echo "Removing old binary $filename..."
        rm -f "$BIN_DIR/$filename"
    fi
done

systemctl daemon-reload

echo "--- Phase 3: Installing New Files ---"

# 4. Create working and log directories
echo "Creating directories..."
mkdir -p "$WORKDIR/logs"
mkdir -p "$LOG_DIR"
chmod 755 "$WORKDIR"
chmod 755 "$LOG_DIR"

# 5. Move Binaries from Temp to Bin Dir
for filename in "${BINARIES[@]}"; do
    mv "$TMP_DIR/$filename" "$BIN_DIR/$filename"
done

# 6. Move Service Files from Temp to Service Dir
for service in "${SERVICES[@]}"; do
    mv "$TMP_DIR/$service" "$SERVICE_DIR/$service"
done

echo "--- Phase 4: Finalizing Installation ---"

# 7. Download and Install Autoinstall Configs
echo "Installing autoinstall configurations..."
mkdir -p "$WORKDIR/autoinstall/etc"

# CMS Apps
curl -fsSL "$DOWNLOAD_URL/autoinstall/etc/cms-apps.json" -o "$WORKDIR/autoinstall/etc/cms-apps.json" || echo "Warning: Failed to download cms-apps.json"

# System Apps (Dynamic discovery via manifest)
curl -fsSL "$DOWNLOAD_URL/autoinstall/etc/manifest.txt" -o "$TMP_DIR/manifest.txt" 2>/dev/null || true
if [ -f "$TMP_DIR/manifest.txt" ]; then
    while IFS= read -r os_file; do
        [ -z "$os_file" ] && continue
        echo "Downloading configuration: $os_file..."
        curl -fsSL "$DOWNLOAD_URL/autoinstall/etc/$os_file" -o "$WORKDIR/autoinstall/etc/$os_file" 2>/dev/null || true
    done < "$TMP_DIR/manifest.txt"
else
    # Fallback if manifest is missing
    for os_name in almalinux debian ubuntu rocky centos fedora; do
        curl -fsSL "$DOWNLOAD_URL/autoinstall/etc/system-$os_name.json" -o "$WORKDIR/autoinstall/etc/system-$os_name.json" 2>/dev/null || true
    done
fi

# 8. Reload systemd and start services
systemctl daemon-reload

for service in "${SERVICES[@]}"; do
    echo "Starting and enabling $service..."
    systemctl enable "$service"
    systemctl start "$service"
done

echo ""
echo "--- Installation Complete ---"
echo "Working directory: $WORKDIR"
echo "Log directory:     $LOG_DIR"
echo "Check status with: systemctl status onifast-*"
