#!/bin/bash

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

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

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

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

check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "Please run as root"
        exit 1
    fi
}

echo "============================================================"
echo "  Aubo Setup Patch Deploy Script"
echo "============================================================"

check_root

log_info "Deploying Aubo setup patch..."

if [ ! -f "setup_astra_linux.sh" ]; then
    log_error "setup_astra_linux.sh not found!"
    exit 1
fi

log_info "Setting execute permissions..."
chmod +x setup_astra_linux.sh

log_info "Verifying script integrity..."
if head -n 1 setup_astra_linux.sh | grep -q "^#!/bin/bash"; then
    log_success "Script is valid"
else
    log_error "Script is invalid"
    exit 1
fi

if [ -f "nginx.zip" ]; then
    log_info "Extracting nginx.zip..."
    unzip -o nginx.zip -d /usr/local/ 2>/dev/null || true
    log_success "Nginx extracted"
fi

echo ""
echo "============================================================"
echo "  Ready to run setup script!"
echo "============================================================"
echo ""
echo "The setup script will:"
echo "  1. Install required packages"
echo "  2. Configure GRUB (requires reboot)"
echo "  3. Install ARCS"
echo "  4. Configure services"
echo ""
read -p "Continue with setup? (y/n): " confirm

if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
    log_info "Aborted by user"
    exit 0
fi

log_info "Starting setup..."
bash setup_astra_linux.sh
