#!/bin/bash

# Arch Hyprland Setup - Base Installer
# Runs all installation scripts in the correct order

set -e  # Exit on any error

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

echo "Starting Arch Hyprland Setup..."

# Make all scripts executable
echo "Making scripts executable..."
find "$SCRIPTS_DIR" -name "*.sh" -type f -exec chmod +x {} \;
echo "✓ All scripts are now executable"

# Function to run a script and check for errors
run_script() {
    local script="$1"
    local name="$2"
    
    if [[ -f "$script" ]]; then
        echo "Running $name..."
        bash "$script"
        echo " $name completed"
    else
        echo "� Warning: $name not found at $script"
    fi
}

# Step 1: Install AUR helper (yay)
run_script "$SCRIPTS_DIR/aur.sh" "AUR helper installation"

# Step 2: System configuration
echo "Configuring system settings..."
run_script "$SCRIPTS_DIR/config/detect-keyboard-layout.sh" "Keyboard layout detection"
run_script "$SCRIPTS_DIR/config/network.sh" "Network configuration"
run_script "$SCRIPTS_DIR/config/nvidia.sh" "NVIDIA configuration"
run_script "$SCRIPTS_DIR/config/power.sh" "Power management"
run_script "$SCRIPTS_DIR/config/fix-fkeys.sh" "Function keys configuration"
run_script "$SCRIPTS_DIR/config/config.sh" "General system configuration"

# Step 3: Copy configuration files
echo "Copying configuration files..."
CONFIG_DIR="$SCRIPT_DIR/config"
if [[ -d "$CONFIG_DIR" ]]; then
    # Create config directories if they don't exist
    mkdir -p "$HOME/.config/hypr"
    
    # Copy hyprland.conf to ~/.config/hypr/
    if [[ -f "$CONFIG_DIR/hyprland.conf" ]]; then
        cp "$CONFIG_DIR/hyprland.conf" "$HOME/.config/hypr/hyprland.conf"
        echo "✓ Hyprland configuration copied"
    fi
    
    echo "✓ Configuration files copied"
else
    echo "⚠ Warning: Config directory not found at $CONFIG_DIR"
fi

# Step 4: Desktop environment
echo "Installing desktop environment..."
run_script "$SCRIPTS_DIR/desktop/fonts.sh" "Font installation"
run_script "$SCRIPTS_DIR/desktop/hyprlandia.sh" "Hyprland installation"
run_script "$SCRIPTS_DIR/desktop/uwsm.sh" "Universal Wayland Session Manager"
run_script "$SCRIPTS_DIR/desktop/desktop.sh" "Desktop applications"
run_script "$SCRIPTS_DIR/desktop/bluetooth.sh" "Bluetooth setup"
run_script "$SCRIPTS_DIR/desktop/theme.sh" "Theme configuration"

# Step 5: Additional software and configurations
echo "Installing additional software..."
run_script "$SCRIPTS_DIR/development.sh" "Development tools"
run_script "$SCRIPTS_DIR/firewall.sh" "Firewall configuration"
run_script "$SCRIPTS_DIR/mimetypes.sh" "MIME types configuration"
run_script "$SCRIPTS_DIR/xtras.sh" "Extra applications"

echo "<� Arch Hyprland Setup completed successfully!"
echo "Please reboot your system to ensure all changes take effect."