#!/bin/bash
# Phantom-WG Bootstrap Installer
# Usage: curl -sSL https://install.phantom.tc | bash
#
# Copyright (c) 2025 Rıza Emre ARAS
# Licensed under AGPL-3.0

set -euo pipefail

# =============================================================================
# CONFIGURATION - Update this URL for each release
# =============================================================================
LATEST_RELEASE_URL="https://github.com/ARAS-Workspace/phantom-wg/releases/download/core-v1.0.5/phantom-wg-retro-core-v1.0.5.zip"
# =============================================================================

# Supported OS versions
SUPPORTED_DEBIAN_VERSIONS=("12" "13")
SUPPORTED_UBUNTU_VERSIONS=("22.04" "24.04")

INSTALL_DIR="/tmp/phantom-install-$(date +%s)"
BOOTSTRAP_SUCCESS=false

# Colors
if [[ -t 1 ]]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    CYAN='\033[0;36m'
    NC='\033[0m'
else
    RED=''
    GREEN=''
    YELLOW=''
    CYAN=''
    NC=''
fi

log() {
    echo -e "${2:-$NC}[$(date '+%H:%M:%S')] $1${NC}"
}

error_exit() {
    log "ERROR: $1" "$RED"
    exit 1
}

print_header() {
    echo -e "${CYAN}"
    echo "██████╗ ██╗  ██╗ █████╗ ███╗   ██╗████████╗ ██████╗ ███╗   ███╗"
    echo "██╔══██╗██║  ██║██╔══██╗████╗  ██║╚══██╔══╝██╔═══██╗████╗ ████║"
    echo "██████╔╝███████║███████║██╔██╗ ██║   ██║   ██║   ██║██╔████╔██║"
    echo "██╔═══╝ ██╔══██║██╔══██║██║╚██╗██║   ██║   ██║   ██║██║╚██╔╝██║"
    echo "██║     ██║  ██║██║  ██║██║ ╚████║   ██║   ╚██████╔╝██║ ╚═╝ ██║"
    echo "╚═╝     ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝   ╚═╝    ╚═════╝ ╚═╝     ╚═╝"
    echo -e "${NC}"
    echo -e "${CYAN}Phantom-WG Bootstrap Installer${NC}"
    echo ""
}

check_root() {
    if [[ $EUID -ne 0 ]]; then
        error_exit "This script must be run as root. Use: curl -sSL https://install.phantom.tc | sudo bash"
    fi
    log "Root privileges confirmed" "$GREEN"
}

check_os() {
    if [[ ! -f /etc/debian_version ]]; then
        error_exit "This script requires Debian/Ubuntu"
    fi

    # shellcheck disable=SC1091
    source /etc/os-release

    OS_ID="$ID"
    OS_VERSION_ID="$VERSION_ID"
    OS_PRETTY_NAME="$PRETTY_NAME"

    log "Detected: $OS_PRETTY_NAME" "$CYAN"

    local supported=false

    case "$OS_ID" in
        debian)
            for version in "${SUPPORTED_DEBIAN_VERSIONS[@]}"; do
                if [[ "$OS_VERSION_ID" == "$version" ]]; then
                    supported=true
                    break
                fi
            done
            if [[ "$supported" == false ]]; then
                error_exit "Debian $OS_VERSION_ID is not supported. Supported: ${SUPPORTED_DEBIAN_VERSIONS[*]}"
            fi
            ;;
        ubuntu)
            for version in "${SUPPORTED_UBUNTU_VERSIONS[@]}"; do
                if [[ "$OS_VERSION_ID" == "$version" ]]; then
                    supported=true
                    break
                fi
            done
            if [[ "$supported" == false ]]; then
                error_exit "Ubuntu $OS_VERSION_ID is not supported. Supported: ${SUPPORTED_UBUNTU_VERSIONS[*]}"
            fi
            ;;
        *)
            error_exit "$OS_ID is not supported. Supported: Debian (${SUPPORTED_DEBIAN_VERSIONS[*]}), Ubuntu (${SUPPORTED_UBUNTU_VERSIONS[*]})"
            ;;
    esac

    log "OS: $OS_PRETTY_NAME [Supported]" "$GREEN"
}

install_unzip() {
    if command -v unzip &> /dev/null; then
        log "unzip is already installed" "$GREEN"
        return
    fi

    log "Installing unzip..." "$YELLOW"
    apt-get update
    apt-get install -y unzip || error_exit "Failed to install unzip"
    log "unzip installed" "$GREEN"
}

check_dependencies() {
    if ! command -v curl &> /dev/null; then
        error_exit "curl is required but not installed"
    fi
    log "curl is available" "$GREEN"
}

download_release() {
    log "Creating installation directory: $INSTALL_DIR" "$YELLOW"
    mkdir -p "$INSTALL_DIR"

    log "Downloading Phantom-WG from: $LATEST_RELEASE_URL" "$YELLOW"
    local archive_path="$INSTALL_DIR/phantom-wg.zip"

    curl -L --progress-bar "$LATEST_RELEASE_URL" -o "$archive_path" || error_exit "Failed to download release archive"

    log "Extracting archive..." "$YELLOW"
    unzip "$archive_path" -d "$INSTALL_DIR" || error_exit "Failed to extract archive"

    rm -f "$archive_path"
    log "Download and extraction complete" "$GREEN"
}

run_installer() {
    local installer_path="$INSTALL_DIR/phantom-install.sh"

    if [[ ! -f "$installer_path" ]]; then
        error_exit "Installer script not found: $installer_path"
    fi

    log "Handing over to phantom-install.sh..." "$CYAN"
    echo ""

    chmod +x "$installer_path"
    cd "$INSTALL_DIR"

    # Run installer - this will handle the actual installation
    ./phantom-install.sh

    # Mark bootstrap as successful after installer completes
    BOOTSTRAP_SUCCESS=true
}

cleanup() {
    if [[ -d "$INSTALL_DIR" ]]; then
        log "Cleaning up temporary files: $INSTALL_DIR" "$YELLOW"
        rm -rf "$INSTALL_DIR"
        log "Cleanup complete" "$GREEN"
    fi
}

cleanup_on_error() {
    if [[ "$BOOTSTRAP_SUCCESS" == false ]]; then
        log "Bootstrap failed, cleaning up..." "$RED"
        cleanup
    fi
}

main() {
    print_header

    log "Starting bootstrap process..." "$CYAN"
    echo ""

    check_root
    check_os
    check_dependencies
    install_unzip

    download_release
    run_installer

    # Cleanup after successful installation
    cleanup

    echo ""
    log "Bootstrap complete!" "$GREEN"
}

# Only cleanup on error, not on normal exit
trap cleanup_on_error ERR

main "$@"