#!/bin/bash
# SMG AIO Downloader Script
# This script downloads and installs the modular SMG AIO system
# Handles: fresh installs, updates, broken repos, missing dependencies
# Version: 3.10.2.8

# Don't exit on error - we handle errors manually
# set -e

# ============================================
# Configuration
# ============================================
BASEURL="https://install.smg.com.tr/SMGaio"
INSTALL_DIR="/opt/smgaio"
TARBALL="smgaio_modular.tar.gz"
LOG_FILE="/var/log/smgaio_install.log"
VERSION="3.10.2.8"

# Expected hash for the tarball (update this when you upload new version)
EXPECTED_HASH="d5237f6bdbdd5508ef55e7c24e58b09de92bfca026d7e1da873fc092322ea6be"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# ============================================
# Logging Functions
# ============================================
log() {
    local msg="[$(date '+%Y-%m-%d %H:%M:%S')] $1"
    echo -e "$msg" | tee -a "$LOG_FILE"
}

log_success() {
    echo -e "${GREEN}✓ $1${NC}" | tee -a "$LOG_FILE"
}

log_warning() {
    echo -e "${YELLOW}⚠ $1${NC}" | tee -a "$LOG_FILE"
}

log_error() {
    echo -e "${RED}✗ $1${NC}" | tee -a "$LOG_FILE"
}

log_info() {
    echo -e "${BLUE}ℹ $1${NC}" | tee -a "$LOG_FILE"
}

# ============================================
# LED Control (SMGBox OpenVFD)
# ============================================
LED_PATH="/sys/devices/platform/openvfd/attr"

led_on() {
    local led="$1"
    [ -f "$LED_PATH/$led" ] && echo 1 | tee "$LED_PATH/$led" > /dev/null 2>&1
}

led_off() {
    local led="$1"
    [ -f "$LED_PATH/$led" ] && echo 0 | tee "$LED_PATH/$led" > /dev/null 2>&1
}

led_all_off() {
    for i in b0 b1 b2 b3 b4 b5 b6; do
        led_off "$i"
    done
}

# LED mapping: b0=: b1=APPS b2=Setup b3=USB b4=CARD b5=HD b6=CVBS
led_setup_on() { led_on "b2"; }
led_setup_off() { led_off "b2"; }
led_apps_on() { led_on "b1"; }
led_apps_off() { led_off "b1"; }

# ============================================
# Root Check
# ============================================
check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        log_error "This script must be run as root (use sudo)"
        echo "Usage: sudo bash $0"
        exit 1
    fi
    log_success "Running as root"
}

# ============================================
# Device Detection
# ============================================
detect_device() {
    local ARCHITECTURE=$(uname -a)
    local SUPPORTED_DEVICES=("meson64" "raspberrypi" "tinkerboard" "smglinux" "x86_64" "i386" "i686" "smgplayer")
    
    for DEVICE in "${SUPPORTED_DEVICES[@]}"; do
        if echo "$ARCHITECTURE" | grep -qi "$DEVICE"; then
            echo "$DEVICE"
            return 0
        fi
    done

    # Fallback: Check architecture
    local ARCH=$(uname -m)
    case "$ARCH" in
        x86_64)
            echo "x86_64"
            return 0
            ;;
        i386|i686)
            echo "i386"
            return 0
            ;;
        armv7l|armhf)
            echo "smgplayer"
            return 0
            ;;
        aarch64|arm64)
            echo "meson64"
            return 0
            ;;
    esac

    log_error "Device not supported: $ARCHITECTURE"
    exit 1
}

# ============================================
# Network Check
# ============================================
check_network() {
    log_info "Checking network connectivity..."
    
    # Try multiple endpoints
    local ENDPOINTS=("8.8.8.8" "1.1.1.1" "google.com")
    local CONNECTED=false
    
    for endpoint in "${ENDPOINTS[@]}"; do
        if ping -c 1 -W 3 "$endpoint" &>/dev/null; then
            CONNECTED=true
            break
        fi
    done
    
    if ! $CONNECTED; then
        log_error "No network connectivity detected"
        log_info "Please check your network connection and try again"
        exit 1
    fi
    
    log_success "Network connectivity OK"
}

# ============================================
# Fix Broken Repos (Debian/Ubuntu)
# ============================================
fix_repositories() {
    log_info "Checking and fixing package repositories..."
    
    local OS_ID=""
    local OS_VERSION=""
    
    # Detect OS
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS_ID="$ID"
        OS_VERSION="$VERSION_CODENAME"
    fi
    
    log_info "Detected OS: $OS_ID ($OS_VERSION)"
    
    # Backup existing sources.list
    if [ -f /etc/apt/sources.list ]; then
        cp /etc/apt/sources.list /etc/apt/sources.list.backup.$(date +%Y%m%d%H%M%S)
        log_info "Backed up existing sources.list"
    fi
    
    # Fix based on OS
    case "$OS_ID" in
        debian)
            fix_debian_repos "$OS_VERSION"
            ;;
        ubuntu)
            fix_ubuntu_repos "$OS_VERSION"
            ;;
        raspbian)
            fix_raspbian_repos "$OS_VERSION"
            ;;
        *)
            log_warning "Unknown OS, attempting generic Debian fix..."
            fix_debian_repos "bullseye"
            ;;
    esac
    
    # Clean and update
    apt-get clean || true
    rm -rf /var/lib/apt/lists/* || true
    
    # Try to update with error handling
    log_info "Updating package lists..."
    apt-get update 2>&1 | tee -a "$LOG_FILE" || true
    
    log_success "Repository fix completed"
}

fix_debian_repos() {
    local VERSION="${1:-bullseye}"
    
    log_info "Setting up Debian $VERSION repositories..."
    
    cat <<EOF > /etc/apt/sources.list
deb http://deb.debian.org/debian $VERSION main
deb-src http://deb.debian.org/debian $VERSION main

deb http://security.debian.org/debian-security $VERSION-security main
deb-src http://security.debian.org/debian-security $VERSION-security main

deb http://deb.debian.org/debian $VERSION-updates main
deb-src http://deb.debian.org/debian $VERSION-updates main
EOF

    # Only add backports for Debian 9 (stretch) and 10 (buster)
    if [ "$VERSION" = "stretch" ] || [ "$VERSION" = "buster" ]; then
        cat <<EOF >> /etc/apt/sources.list

deb http://deb.debian.org/debian $VERSION-backports main
deb-src http://deb.debian.org/debian $VERSION-backports main
EOF
        log_info "Backports repository added for Debian $VERSION"
    fi
}

fix_ubuntu_repos() {
    local VERSION="${1:-focal}"
    
    log_info "Setting up Ubuntu $VERSION repositories..."
    
    cat > /etc/apt/sources.list << EOF
# Ubuntu $VERSION repositories
deb http://archive.ubuntu.com/ubuntu $VERSION main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu $VERSION-updates main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu $VERSION-security main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu $VERSION-backports main restricted universe multiverse
EOF
}

fix_raspbian_repos() {
    local VERSION="${1:-bullseye}"
    
    log_info "Setting up Raspbian $VERSION repositories..."
    
    cat > /etc/apt/sources.list << EOF
# Raspbian $VERSION repositories
deb http://raspbian.raspberrypi.org/raspbian/ $VERSION main contrib non-free rpi
EOF
    
    # Also fix raspi.list if exists
    if [ -d /etc/apt/sources.list.d ]; then
        cat > /etc/apt/sources.list.d/raspi.list << EOF
deb http://archive.raspberrypi.org/debian/ $VERSION main
EOF
    fi
}

# ============================================
# Install Dependencies
# ============================================
install_dependencies() {
    log_info "Installing required dependencies..."
    
    # Essential packages list
    local PACKAGES=(
        "build-essential"
        "wget"
        "curl"
        "whiptail"
        "tar"
        "gzip"
        "coreutils"
        "ca-certificates"
        "gnupg"
        "apt-transport-https"
        "unzip"
    )
    
    # Update package lists (ignore errors)
    apt-get update -qq || true
    
    # Install packages one by one to handle failures gracefully
    for pkg in "${PACKAGES[@]}"; do
        if dpkg -s "$pkg" &>/dev/null; then
            log_success "$pkg is already installed"
        else
            log_info "Installing $pkg..."
            if apt-get install -y "$pkg" &>/dev/null; then
                log_success "$pkg installed successfully"
            else
                log_warning "Failed to install $pkg, continuing..."
            fi
        fi
    done
    
    # GCC - Required for shc compilation
    if command -v gcc &>/dev/null; then
        log_success "gcc is already installed: $(gcc --version | head -n1)"
    else
        log_info "Installing gcc..."
        apt-get install -y gcc
        if command -v gcc &>/dev/null; then
            log_success "gcc installed successfully"
        else
            log_error "gcc installation failed - binary compilation won't work"
        fi
    fi
    
    # SHC - Shell Script Compiler (REQUIRED for security)
    if command -v shc &>/dev/null; then
        log_success "shc is already installed: $(shc -v 2>&1 | head -n1 || echo 'version unknown')"
    else
        log_info "Installing shc (required for binary compilation)..."
        if apt-get install -y shc; then
            log_success "shc installed successfully"
        else
            log_warning "shc not available in repos, trying alternative installation..."
            # Try building from source if package not available
            install_shc_from_source
        fi
    fi
    
    # Verify both are installed
    if ! command -v gcc &>/dev/null || ! command -v shc &>/dev/null; then
        log_error "Critical dependencies missing!"
        log_error "gcc: $(command -v gcc &>/dev/null && echo 'OK' || echo 'MISSING')"
        log_error "shc: $(command -v shc &>/dev/null && echo 'OK' || echo 'MISSING')"
        
        if ! whiptail --yesno "Some critical tools are missing.\n\nInstallation will continue but binary compilation may fail.\n\nContinue anyway?" 12 60; then
            log_info "Installation cancelled by user"
            exit 1
        fi
    fi
    
    log_success "Dependencies installation completed"
}

# ============================================
# Install SHC from source (fallback)
# ============================================
install_shc_from_source() {
    log_info "Building SHC from source..."
    
    local BUILD_DIR="/tmp/shc_build_$$"
    mkdir -p "$BUILD_DIR"
    cd "$BUILD_DIR"
    
    # Download SHC source
    if wget -q https://github.com/neurobin/shc/archive/refs/tags/4.0.3.tar.gz -O shc.tar.gz 2>/dev/null; then
        tar -xzf shc.tar.gz
        cd shc-4.0.3 || cd shc-* 2>/dev/null
        
        # Build and install
        if ./configure && make && make install 2>/dev/null; then
            log_success "SHC installed from source"
        else
            log_error "Failed to build SHC from source"
        fi
    else
        log_error "Failed to download SHC source"
    fi
    
    # Cleanup
    cd /
    rm -rf "$BUILD_DIR"
}

# ============================================
# Device-Specific Setup
# ============================================
setup_device() {
    local DEVICE=$1
    
    log_info "Running device-specific setup for: $DEVICE"
    
    case "$DEVICE" in
        "meson64")
            setup_smgbox
            ;;
        "raspberrypi")
            setup_raspberry_pi
            ;;
        "tinkerboard")
            setup_tinkerboard
            ;;
        "smglinux"|"smgplayer")
            setup_arm_generic
            ;;
        "x86_64"|"i386"|"i686")
            setup_x86
            ;;
    esac
}

setup_smgbox() {
    log_info "Configuring SMGBox (meson64)..."
    
    # SMGBox specific: Force Debian Bullseye repos
    fix_debian_repos "bullseye"
    
    # Update and upgrade (ignore errors)
    apt-get update || true
    apt-get upgrade -y || true
    
    log_success "SMGBox configuration completed"
}

setup_raspberry_pi() {
    log_info "Configuring Raspberry Pi..."
    
    # Detect Raspbian version
    local VERSION="bullseye"
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        VERSION="${VERSION_CODENAME:-bullseye}"
    fi
    
    fix_raspbian_repos "$VERSION"
    
    # Install RPi specific packages
    apt-get update || true
    apt-get install -y raspi-config || true
    
    log_success "Raspberry Pi configuration completed"
}

setup_tinkerboard() {
    log_info "Configuring Tinkerboard..."
    
    # Tinkerboard usually runs Armbian
    fix_debian_repos "bullseye"
    
    apt-get update || true
    
    log_success "Tinkerboard configuration completed"
}

setup_arm_generic() {
    log_info "Configuring ARM device..."
    
    fix_debian_repos "bullseye"
    apt-get update || true
    
    log_success "ARM device configuration completed"
}

setup_x86() {
    log_info "Configuring x86/x64 device..."
    
    # Detect if Debian or Ubuntu
    local OS_ID=""
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS_ID="$ID"
    fi
    
    if [ "$OS_ID" = "ubuntu" ]; then
        fix_ubuntu_repos
    else
        fix_debian_repos "bullseye"
    fi
    
    apt-get update || true
    
    log_success "x86/x64 device configuration completed"
}

# ============================================
# Hash Verification
# ============================================
check_hash() {
    local file=$1
    
    # Skip hash check if EXPECTED_HASH is empty
    if [ -z "$EXPECTED_HASH" ]; then
        log_warning "Hash check skipped (no expected hash defined)"
        return 0
    fi
    
    log_info "Verifying file integrity..."
    local downloaded_hash=$(sha256sum "$file" | awk '{ print $1 }')

    if [ "$downloaded_hash" != "$EXPECTED_HASH" ]; then
        log_error "Hash verification failed!"
        log_error "Expected: $EXPECTED_HASH"
        log_error "Got: $downloaded_hash"
        exit 1
    fi
    
    log_success "Hash verification passed"
}

# ============================================
# Download and Install
# ============================================
download_and_install() {
    local DEVICE=$1
    
    echo ""
    echo "=========================================="
    echo "  SMG AIO Modular Installation v$VERSION"
    echo "  Device: $DEVICE"
    echo "=========================================="
    echo ""
    
    # Check if already installed
    if [ -d "$INSTALL_DIR" ] && [ -f "$INSTALL_DIR/smgaio_modular" ]; then
        log_warning "SMG AIO is already installed at $INSTALL_DIR"
        if ! whiptail --yesno "SMG AIO is already installed. Do you want to reinstall/update?" 8 60; then
            log_info "Installation cancelled by user"
            exit 0
        fi
        log_info "Removing old installation..."
        rm -rf "$INSTALL_DIR"
    fi
    
    # Create installation directory
    mkdir -p "$INSTALL_DIR"
    
    # Download with retry
    cd /tmp
    local MAX_RETRIES=3
    local RETRY=0
    local DOWNLOAD_SUCCESS=false
    
    while [ $RETRY -lt $MAX_RETRIES ] && [ "$DOWNLOAD_SUCCESS" = "false" ]; do
        log_info "Downloading SMG AIO package (attempt $((RETRY+1))/$MAX_RETRIES)..."
        
        if wget -q --show-progress --timeout=30 "$BASEURL/$TARBALL" -O "$TARBALL" 2>&1; then
            if [ -f "$TARBALL" ] && [ -s "$TARBALL" ]; then
                DOWNLOAD_SUCCESS=true
                log_success "Download completed"
            fi
        fi
        
        if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
            RETRY=$((RETRY+1))
            if [ $RETRY -lt $MAX_RETRIES ]; then
                log_warning "Download failed, retrying in 5 seconds..."
                sleep 5
            fi
        fi
    done
    
    if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
        log_error "Download failed after $MAX_RETRIES attempts"
        log_error "Please check your internet connection and try again"
        exit 1
    fi
    
    # Verify hash
    check_hash "$TARBALL"
    
    # Extract to installation directory
    log_info "Extracting to $INSTALL_DIR..."
    tar -xzf "$TARBALL" -C "$INSTALL_DIR" --strip-components=1
    
    if [ $? -ne 0 ]; then
        log_error "Extraction failed"
        exit 1
    fi
    
    # Fix ownership to root (in case of macOS build artifacts)
    log_info "Setting ownership to root..."
    chown -R root:root "$INSTALL_DIR" 2>/dev/null || chown -R root:0 "$INSTALL_DIR" 2>/dev/null
    
    # Clean up any macOS metadata files
    find "$INSTALL_DIR" -name "._*" -delete 2>/dev/null
    find "$INSTALL_DIR" -name ".DS_Store" -delete 2>/dev/null
    
    # Set permissions
    log_info "Setting permissions..."
    chmod +x "$INSTALL_DIR/smgaio_modular.sh"
    
    # Compile to binary (REQUIRED for security)
    log_info "Compiling main script to binary..."
    if ! command -v shc &>/dev/null; then
        log_error "SHC not found - cannot compile binary!"
        log_error "Installation incomplete. Please install shc and try again."
        exit 1
    fi
    
    cd "$INSTALL_DIR"
    if shc -f smgaio_modular.sh -o smgaio_modular 2>/dev/null; then
        if [ -f "$INSTALL_DIR/smgaio_modular" ]; then
            chmod +x "$INSTALL_DIR/smgaio_modular"
            rm -f smgaio_modular.sh.x.c  # Cleanup C source
            rm -f smgaio_modular.sh      # Remove source script after compilation
            log_success "Binary compilation successful (source removed)"
        else
            log_error "Binary file not created"
            exit 1
        fi
    else
        log_error "Binary compilation failed"
        exit 1
    fi
    
    # Create symlink for easy access
    log_info "Creating symlink..."
    mkdir -p /usr/local/bin
    ln -sf "$INSTALL_DIR/smgaio_modular" /usr/local/bin/smgaio
    
    # Cleanup
    rm -f "$TARBALL"
    
    echo ""
    echo "=========================================="
    log_success "Installation Complete!"
    echo "=========================================="
    echo ""
    echo "  Installation path: $INSTALL_DIR"
    echo "  Run with: sudo smgaio"
    echo "  Or: sudo $INSTALL_DIR/smgaio_modular"
    echo ""
    echo "  Log file: $LOG_FILE"
    echo "=========================================="
    echo ""
    
    # Inform user to run manually for clean environment
    whiptail --title "Installation Complete" --msgbox "SMG AIO installed successfully!\n\nPlease run with:\n\n  sudo smgaio\n\nThis ensures proper permissions and clean environment." 14 55
}

# ============================================
# Cleanup on Error
# ============================================
cleanup_on_error() {
    log_error "Installation failed!"
    log_info "Cleaning up..."
    rm -f /tmp/"$TARBALL"
    log_info "Check log file for details: $LOG_FILE"
    exit 1
}

# Set trap for cleanup
trap cleanup_on_error ERR

# ============================================
# Check if already installed (Update Mode)
# ============================================
check_existing_installation() {
    if [ -d "$INSTALL_DIR" ] && [ -f "$INSTALL_DIR/smgaio_modular" ]; then
        return 0  # Already installed
    fi
    return 1  # Not installed
}

# ============================================
# Update existing installation - Wget (Online)
# ============================================
update_wget() {
    log_info "Existing installation found. Running update..."
    
    # Backup current version
    local BACKUP_DIR="/tmp/smgaio_backup_$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$BACKUP_DIR"
    cp -r "$INSTALL_DIR"/* "$BACKUP_DIR/" 2>/dev/null || true
    log_info "Backup created: $BACKUP_DIR"
    
    # Download new version
    log_info "Downloading update from $BASEURL/$TARBALL"
    cd /tmp
    rm -f "$TARBALL"
    
    if ! wget -q "$BASEURL/$TARBALL" -O "$TARBALL"; then
        log_error "Failed to download update"
        return 1
    fi
    
    # Verify hash
    local DOWNLOADED_HASH=$(sha256sum "$TARBALL" | awk '{print $1}')
    if [ "$DOWNLOADED_HASH" != "$EXPECTED_HASH" ]; then
        log_error "Hash mismatch! Update aborted."
        log_error "Expected: $EXPECTED_HASH"
        log_error "Got: $DOWNLOADED_HASH"
        return 1
    fi
    log_success "Hash verified"
    
    # Extract and update
    rm -rf /tmp/smgaio_modular
    tar -xzf "$TARBALL" -C /tmp/
    
    # Update files (preserve any local configs if needed)
    rm -rf "$INSTALL_DIR/src"
    rm -f "$INSTALL_DIR/.modules_deployed"
    cp /tmp/smgaio_modular/smgaio_modular.sh "$INSTALL_DIR/"
    cp /tmp/smgaio_modular/smgaio_modules.tar.gz.enc "$INSTALL_DIR/"
    chmod +x "$INSTALL_DIR/smgaio_modular.sh"
    
    # Recompile binary
    log_info "Recompiling binary..."
    if ! command -v shc &>/dev/null; then
        log_error "SHC not found - cannot recompile binary!"
        return 1
    fi
    
    cd "$INSTALL_DIR"
    if shc -f smgaio_modular.sh -o smgaio_modular 2>/dev/null; then
        if [ -f "$INSTALL_DIR/smgaio_modular" ]; then
            chmod +x "$INSTALL_DIR/smgaio_modular"
            rm -f smgaio_modular.sh.x.c
            rm -f smgaio_modular.sh      # Remove source script
            log_success "Binary recompiled successfully (source removed)"
        else
            log_error "Binary not created"
            return 1
        fi
    else
        log_error "Recompilation failed"
        return 1
    fi
    
    # Cleanup
    rm -rf /tmp/smgaio_modular "$TARBALL"
    
    log_success "Update completed successfully!"
    
    echo ""
    echo "=========================================="
    echo "  SMG AIO Updated Successfully!"
    echo "=========================================="
    echo ""
    echo "  Run with: sudo smgaio"
    echo ""
    echo "=========================================="
    
    return 0
}

# ============================================
# Update existing installation - FTP (Offline)
# Teknisyen FTP ile dosyayi ~/smgaio_modular.tar.gz
# olarak atar, bu fonksiyon oradan yukler.
# .enc dosyasi paketin icinde gelir (build tarafindan uretilir)
# ============================================
update_ftp() {
    log_info "FTP (Offline) update mode selected..."

    # sudo ile calistiran kullanicinin home dizinini belirle
    local USER_HOME
    if [ -n "$SUDO_USER" ] && [ "$SUDO_USER" != "root" ]; then
        USER_HOME="/home/$SUDO_USER"
    else
        # Dogrudan root olarak calistirilmis
        USER_HOME="/root"
    fi

    log_info "Looking for update package in: $USER_HOME"

    local LOCAL_TARBALL="$USER_HOME/smgaio_modular.tar.gz"

    if [ ! -f "$LOCAL_TARBALL" ]; then
        log_error "Update package not found: $LOCAL_TARBALL"
        whiptail --title "FTP Update - Error" --msgbox \
            "Update package not found!\n\nPlease place the file in:\n\n  $USER_HOME/smgaio_modular.tar.gz\n\nYou can transfer it via FTP to that location." \
            14 60
        return 1
    fi

    log_info "Package found: $LOCAL_TARBALL"

    # Hash dogrulama (EXPECTED_HASH doluysa kontrol et)
    if [ -n "$EXPECTED_HASH" ]; then
        log_info "Verifying file integrity..."
        local DOWNLOADED_HASH
        DOWNLOADED_HASH=$(sha256sum "$LOCAL_TARBALL" | awk '{print $1}')
        if [ "$DOWNLOADED_HASH" != "$EXPECTED_HASH" ]; then
            log_error "Hash mismatch!"
            log_error "Expected: $EXPECTED_HASH"
            log_error "Got:      $DOWNLOADED_HASH"
            if ! whiptail --title "Hash Mismatch" --yesno \
                "File hash does NOT match the expected value.\n\nThis may indicate a corrupted or wrong version file.\n\nContinue anyway (not recommended)?" \
                12 60; then
                return 1
            fi
        else
            log_success "Hash verified"
        fi
    else
        log_warning "Hash check skipped (EXPECTED_HASH not set)"
    fi

    # Backup
    local BACKUP_DIR="/tmp/smgaio_backup_$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$BACKUP_DIR"
    cp -r "$INSTALL_DIR"/* "$BACKUP_DIR/" 2>/dev/null || true
    log_info "Backup created: $BACKUP_DIR"

    # Paketi ac
    log_info "Extracting package..."
    rm -rf /tmp/smgaio_modular
    if ! tar -xzf "$LOCAL_TARBALL" -C /tmp/; then
        log_error "Extraction failed"
        return 1
    fi

    # Dosyalari guncelle
    rm -rf "$INSTALL_DIR/src"
    rm -f "$INSTALL_DIR/.modules_deployed"

    if [ -f /tmp/smgaio_modular/smgaio_modular.sh ]; then
        cp /tmp/smgaio_modular/smgaio_modular.sh "$INSTALL_DIR/"
    else
        log_error "smgaio_modular.sh not found in package"
        return 1
    fi

    # Sifreli modul dosyasi paketin icinden gelir (build tarafindan uretildi)
    if [ -f /tmp/smgaio_modular/smgaio_modules.tar.gz.enc ]; then
        cp /tmp/smgaio_modular/smgaio_modules.tar.gz.enc "$INSTALL_DIR/"
        log_info "Using .enc file from package"
    else
        log_warning "smgaio_modules.tar.gz.enc not found in package - keeping existing"
    fi

    chmod +x "$INSTALL_DIR/smgaio_modular.sh"

    # Binary yeniden derle
    log_info "Recompiling binary..."
    if ! command -v shc &>/dev/null; then
        log_error "SHC not found - cannot recompile binary!"
        return 1
    fi

    cd "$INSTALL_DIR"
    if shc -f smgaio_modular.sh -o smgaio_modular 2>/dev/null; then
        if [ -f "$INSTALL_DIR/smgaio_modular" ]; then
            chmod +x "$INSTALL_DIR/smgaio_modular"
            rm -f smgaio_modular.sh.x.c
            rm -f smgaio_modular.sh
            log_success "Binary recompiled successfully (source removed)"
        else
            log_error "Binary not created"
            return 1
        fi
    else
        log_error "Recompilation failed"
        return 1
    fi

    # Gecici dosyalari temizle
    rm -rf /tmp/smgaio_modular

    # Kullanicinin home dizinindeki update paketini temizle
    log_info "Cleaning up update package from $USER_HOME..."
    rm -f "$USER_HOME/smgaio_modular.tar.gz" 2>/dev/null || true

    log_success "FTP update completed successfully!"

    echo ""
    echo "=========================================="
    echo "  SMG AIO Updated (FTP/Offline) - OK!"
    echo "=========================================="
    echo ""
    echo "  Run with: sudo smgaio"
    echo ""
    echo "=========================================="

    return 0
}

# ============================================
# Main Function
# ============================================
main() {
    # Turn on Setup LED (SMGBox only)
    led_setup_on
    
    # Initialize log
    mkdir -p "$(dirname "$LOG_FILE")"
    echo "" >> "$LOG_FILE"
    log "=========================================="
    log "SMG AIO Installation Started - v$VERSION"
    log "=========================================="
    
    # Check root
    check_root
    
    # Check if already installed - run update instead
    if check_existing_installation; then
        # Guncelleme yontemi secimi
        UPDATE_METHOD=$(whiptail --title "SMG AIO - Update" \
            --menu "SMG AIO is already installed (v$VERSION).\n\nSelect update method:" \
            14 60 3 \
            "1" "Wget  - Online  (download from server)" \
            "2" "FTP   - Offline (use files in ~/updatesmgaio/)" \
            "3" "Cancel - exit without updating" \
            3>&1 1>&2 2>&3)

        local EXIT_CODE=$?
        # ESC veya Cancel basildi
        if [ $EXIT_CODE -ne 0 ] || [ "$UPDATE_METHOD" = "3" ]; then
            whiptail --title "SMG AIO" --msgbox "Update cancelled.\n\nRun 'sudo smgaio' to use existing installation." 10 55
            led_setup_off
            exit 0
        fi

        case "$UPDATE_METHOD" in
            1)
                log_info "Update method: Wget (Online)"
                if update_wget; then
                    led_setup_off
                    self_delete
                    exit 0
                else
                    log_error "Wget update failed"
                    led_setup_off
                    exit 1
                fi
                ;;
            2)
                log_info "Update method: FTP (Offline)"
                if update_ftp; then
                    led_setup_off
                    self_delete
                    exit 0
                else
                    log_error "FTP update failed"
                    led_setup_off
                    exit 1
                fi
                ;;
        esac
    fi
    
    # Detect device
    log_info "Detecting device..."
    DEVICE=$(detect_device)
    log_success "Device detected: $DEVICE"
    
    # Check network
    check_network
    
    # Fix repositories
    fix_repositories
    
    # Device-specific setup
    setup_device "$DEVICE"
    
    # Install dependencies
    install_dependencies
    
    # Download and install
    download_and_install "$DEVICE"
    
    log "=========================================="
    log "SMG AIO Installation Completed Successfully"
    log "=========================================="
    
    # Turn off Setup LED
    led_setup_off
    
    # Self-delete: Remove the downloader script after successful installation
    self_delete
}

# ============================================
# Self Delete Function - STRONG VERSION
# ============================================
self_delete() {
    local SCRIPT_PATH="$(realpath "$0" 2>/dev/null || echo "$0")"
    local SCRIPT_NAME="$(basename "$0")"
    local SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
    
    log_info "=== Self-Delete Check ==="
    log_info "Script path: $SCRIPT_PATH"
    log_info "Install dir: $INSTALL_DIR"
    
    # Step 1: Verify installation exists
    if [ ! -d "$INSTALL_DIR" ]; then
        log_error "Installation directory not found: $INSTALL_DIR"
        log_warning "Keeping installer script for retry"
        return 1
    fi
    
    if [ ! -f "$INSTALL_DIR/smgaio_modular" ]; then
        log_error "Main script not found: $INSTALL_DIR/smgaio_modular"
        log_warning "Keeping installer script for retry"
        return 1
    fi
    
    # Step 2: Verify main script is executable
    if [ ! -x "$INSTALL_DIR/smgaio_modular" ]; then
        chmod +x "$INSTALL_DIR/smgaio_modular" 2>/dev/null
    fi
    
    log_success "Installation verified at $INSTALL_DIR"
    
    # Step 3: Don't delete if running from installed directory
    if [[ "$SCRIPT_PATH" == "$INSTALL_DIR"* ]]; then
        log_info "Running from install directory, not deleting"
        return 0
    fi
    
    # Step 4: Multiple deletion methods for reliability
    log_info "Scheduling installer removal..."
    
    # Method 1: Create a cleanup script that runs after this script exits
    local CLEANUP_SCRIPT="/tmp/.smgaio_cleanup_$$.sh"
    cat > "$CLEANUP_SCRIPT" << CLEANUP_EOF
#!/bin/bash
sleep 3
# Try multiple times
for i in 1 2 3; do
    if [ -f "$SCRIPT_PATH" ]; then
        rm -f "$SCRIPT_PATH" 2>/dev/null
        sync
    fi
    sleep 1
done
# Also check common download locations
rm -f "/tmp/$SCRIPT_NAME" 2>/dev/null
rm -f "/root/$SCRIPT_NAME" 2>/dev/null
rm -f "/home/smg/$SCRIPT_NAME" 2>/dev/null
rm -f "/home/*/$SCRIPT_NAME" 2>/dev/null
rm -f "\$HOME/$SCRIPT_NAME" 2>/dev/null
# Self-destruct cleanup script
rm -f "$CLEANUP_SCRIPT" 2>/dev/null
CLEANUP_EOF
    
    chmod +x "$CLEANUP_SCRIPT"
    nohup "$CLEANUP_SCRIPT" > /dev/null 2>&1 &
    
    # Method 2: Also use trap to delete on exit
    trap "rm -f '$SCRIPT_PATH' 2>/dev/null; rm -f '$CLEANUP_SCRIPT' 2>/dev/null" EXIT
    
    # Method 3: Background deletion as backup
    (sleep 5 && rm -f "$SCRIPT_PATH" 2>/dev/null) &
    
    log_success "Installer will be removed after exit"
    log_info "Installation complete! Run \"sudo smgaio\" to start."
    
    return 0
}

# Run main
main "$@"
