#!/bin/bash
#===============================================================================
# Basilisk II Auto-Installer
# Installe, compile et configure Basilisk II sur Arch Linux ou Debian/Ubuntu
#===============================================================================

set -e

#-------------------------------------------------------------------------------
# Configuration
#-------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROM_SOURCE="${SCRIPT_DIR}/Quadra.ROM"
HDD_SOURCE="${SCRIPT_DIR}/HDD.img"

INSTALL_DIR="${HOME}/.basilisk2"
ROM_FILE="${INSTALL_DIR}/Quadra.ROM"
HDD_FILE="${INSTALL_DIR}/HDD.img"
CONFIG_FILE="${INSTALL_DIR}/basilisk2_prefs"
SHARED_DIR="${INSTALL_DIR}/shared"

#-------------------------------------------------------------------------------
# Options d'installation (modifiées par le menu interactif)
#-------------------------------------------------------------------------------
OPT_SCREEN_RES="800/600"
OPT_COLOR_DEPTH="8"
OPT_RAM_SIZE="16777216"
OPT_AUTOSTART="false"
OPT_SOUND="true"
OPT_NETWORK="false"
INTERACTIVE_MODE="true"

#-------------------------------------------------------------------------------
# Parsing des arguments CLI
#-------------------------------------------------------------------------------
parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            -y|--non-interactive)
                INTERACTIVE_MODE="false"
                shift
                ;;
            -h|--help)
                echo "Usage: $0 [-y|--non-interactive] [-h|--help]"
                echo ""
                echo "Options:"
                echo "  -y, --non-interactive  Installation automatique avec valeurs par défaut"
                echo "  -h, --help             Affiche cette aide"
                exit 0
                ;;
            *)
                echo "Option inconnue: $1"
                echo "Utilisez -h pour l'aide"
                exit 1
                ;;
        esac
    done
}

#-------------------------------------------------------------------------------
# Menu interactif
#-------------------------------------------------------------------------------
ask_choice() {
    local prompt="$1"
    shift
    local options=("$@")
    local default_index=1

    echo
    echo "${prompt}"
    for i in "${!options[@]}"; do
        echo "  $((i+1))) ${options[$i]}"
    done

    local choice
    read -p "Choix [${default_index}]: " choice
    choice=${choice:-${default_index}}

    # Valider l'entrée
    if ! [[ "$choice" =~ ^[0-9]+$ ]] || [ "$choice" -lt 1 ] || [ "$choice" -gt "${#options[@]}" ]; then
        choice=${default_index}
    fi

    echo $((choice-1))
}

interactive_menu() {
    echo
    echo "=== Configuration de l'installation ==="

    # Résolution d'écran
    local resolutions=("640x480 (VGA)" "800x600 (SVGA) [défaut]" "1024x768 (XGA)" "1280x1024 (SXGA)")
    local res_values=("640/480" "800/600" "1024/768" "1280/1024")
    local res_choice=$(ask_choice "Résolution d'écran:" "${resolutions[@]}")
    OPT_SCREEN_RES="${res_values[$res_choice]}"

    # Profondeur de couleur
    local depths=("8 bits (256 couleurs) [défaut]" "16 bits (65K couleurs)" "24 bits (16M couleurs)")
    local depth_values=("8" "16" "24")
    local depth_choice=$(ask_choice "Profondeur de couleur:" "${depths[@]}")
    OPT_COLOR_DEPTH="${depth_values[$depth_choice]}"

    # Mémoire RAM
    local rams=("8 Mo" "16 Mo [défaut]" "32 Mo" "64 Mo")
    local ram_values=("8388608" "16777216" "33554432" "67108864")
    local ram_choice=$(ask_choice "Mémoire RAM:" "${rams[@]}")
    OPT_RAM_SIZE="${ram_values[$ram_choice]}"

    # Démarrage automatique
    echo
    read -p "Démarrer automatiquement au boot? [o/N]: " autostart
    [[ "$autostart" =~ ^[oOyY]$ ]] && OPT_AUTOSTART="true"

    # Son
    read -p "Activer le son? [O/n]: " sound
    [[ "$sound" =~ ^[nN]$ ]] && OPT_SOUND="false"

    # Réseau
    read -p "Activer le réseau? [o/N]: " network
    [[ "$network" =~ ^[oOyY]$ ]] && OPT_NETWORK="true"

    echo
    echo ">>> Configuration choisie:"
    echo "    Écran: ${OPT_SCREEN_RES}/${OPT_COLOR_DEPTH}"
    echo "    RAM: $((OPT_RAM_SIZE/1048576)) Mo"
    echo "    Autostart: ${OPT_AUTOSTART}"
    echo "    Son: ${OPT_SOUND}"
    echo "    Réseau: ${OPT_NETWORK}"
    echo
}

#-------------------------------------------------------------------------------
# Détection de la distribution
#-------------------------------------------------------------------------------
detect_distro() {
    if [ -f /etc/arch-release ]; then
        echo "arch"
    elif [ -f /etc/debian_version ]; then
        echo "debian"
    else
        echo "unknown"
    fi
}

#-------------------------------------------------------------------------------
# Installation des dépendances
#-------------------------------------------------------------------------------
install_deps_arch() {
    echo ">>> Installation des dépendances (Arch)..."
    sudo pacman -S --needed --noconfirm \
        base-devel git sdl2 gtk2 \
        autoconf automake pkg-config \
        xorg-server libx11 libxext
}

install_deps_debian() {
    echo ">>> Installation des dépendances (Debian/Ubuntu)..."
    sudo apt-get update
    sudo apt-get install -y \
        build-essential git libsdl2-dev libgtk2.0-dev \
        autoconf automake pkg-config wget \
        xserver-xorg libx11-dev libxext-dev
}

#-------------------------------------------------------------------------------
# Compilation de Basilisk II
#-------------------------------------------------------------------------------
compile_basilisk() {
    echo ">>> Compilation de Basilisk II..."
    
    local build_dir="/tmp/basilisk2-build"
    rm -rf "${build_dir}"
    mkdir -p "${build_dir}"
    cd "${build_dir}"
    
    git clone --depth 1 https://github.com/cebix/macemu.git
    cd macemu/BasiliskII/src/Unix
    
    ./autogen.sh
    ./configure --enable-sdl-video --enable-sdl-audio --with-gtk=gtk2
    make -j$(nproc)
    
    # Installation du binaire
    mkdir -p "${INSTALL_DIR}/bin"
    cp BasiliskII "${INSTALL_DIR}/bin/"
    
    echo ">>> Compilation terminée"
    cd /
    rm -rf "${build_dir}"
}

#-------------------------------------------------------------------------------
# Copie des ressources depuis le repo local
#-------------------------------------------------------------------------------
copy_resources() {
    echo ">>> Copie de la ROM et de l'image disque..."

    mkdir -p "${INSTALL_DIR}"
    mkdir -p "${SHARED_DIR}"

    if [ ! -f "${ROM_SOURCE}" ]; then
        echo "ERREUR: ROM non trouvée: ${ROM_SOURCE}"
        exit 1
    fi

    if [ ! -f "${HDD_SOURCE}" ]; then
        echo "ERREUR: Image disque non trouvée: ${HDD_SOURCE}"
        exit 1
    fi

    cp -v "${ROM_SOURCE}" "${ROM_FILE}"
    cp -v "${HDD_SOURCE}" "${HDD_FILE}"

    echo ">>> Fichiers copiés"
}

#-------------------------------------------------------------------------------
# Génération de la configuration
#-------------------------------------------------------------------------------
generate_config() {
    echo ">>> Génération de la configuration..."

    # Calcul des valeurs booléennes inversées pour Basilisk II
    local nosound="false"
    local nonet="true"
    [[ "${OPT_SOUND}" == "false" ]] && nosound="true"
    [[ "${OPT_NETWORK}" == "true" ]] && nonet="false"

    cat > "${CONFIG_FILE}" << EOF
# Basilisk II Configuration
# Généré automatiquement

# ROM et disque
rom ${ROM_FILE}
disk ${HDD_FILE}

# Mémoire ($((OPT_RAM_SIZE/1048576)) Mo)
ramsize ${OPT_RAM_SIZE}

# Modèle Quadra 900
modelid 14
cpu 4
fpu true

# Affichage (${OPT_SCREEN_RES}, ${OPT_COLOR_DEPTH} bits)
screen dga/${OPT_SCREEN_RES}/${OPT_COLOR_DEPTH}
frameskip 1

# Audio
nosound ${nosound}

# Réseau
nonet ${nonet}

# Dossier partagé avec l'hôte
extfs ${SHARED_DIR}

# Presse-papier partagé
enableextfs true
EOF

    echo ">>> Configuration générée: ${CONFIG_FILE}"
}

#-------------------------------------------------------------------------------
# Création du lanceur
#-------------------------------------------------------------------------------
create_launcher() {
    echo ">>> Création des lanceurs..."
    
    # Script de lancement
    local launcher="${INSTALL_DIR}/run.sh"
    cat > "${launcher}" << EOF
#!/bin/bash
cd "${INSTALL_DIR}"
exec "${INSTALL_DIR}/bin/BasiliskII" --config "${CONFIG_FILE}"
EOF
    chmod +x "${launcher}"
    
    # Lien symbolique dans ~/bin si existe
    if [ -d "${HOME}/bin" ]; then
        ln -sf "${launcher}" "${HOME}/bin/basilisk2"
        echo "    Lien créé: ~/bin/basilisk2"
    fi
    
    # Fichier .desktop
    local desktop_file="${HOME}/.local/share/applications/basilisk2.desktop"
    mkdir -p "$(dirname "${desktop_file}")"
    cat > "${desktop_file}" << EOF
[Desktop Entry]
Name=Basilisk II
Comment=Émulateur Macintosh 68k - System 7
Exec=${launcher}
Icon=computer
Terminal=false
Type=Application
Categories=Emulator;System;
EOF

    echo "    Raccourci bureau créé"
}

#-------------------------------------------------------------------------------
# Configuration du démarrage automatique (systemd)
#-------------------------------------------------------------------------------
setup_autostart() {
    if [ "${OPT_AUTOSTART}" != "true" ]; then
        return
    fi

    echo ">>> Configuration du démarrage automatique..."

    local service_dir="${HOME}/.config/systemd/user"
    mkdir -p "${service_dir}"

    cat > "${service_dir}/basilisk2.service" << EOF
[Unit]
Description=Basilisk II Macintosh Emulator
After=graphical-session.target

[Service]
ExecStart=${INSTALL_DIR}/run.sh
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
EOF

    systemctl --user daemon-reload
    systemctl --user enable basilisk2.service

    echo "    Service systemd activé: basilisk2.service"
    echo "    Démarrer manuellement: systemctl --user start basilisk2"
}

#-------------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------------
main() {
    echo "=============================================="
    echo "  Basilisk II - Installation automatique"
    echo "=============================================="
    echo

    # Menu interactif si pas en mode -y
    if [ "${INTERACTIVE_MODE}" = "true" ]; then
        interactive_menu
    fi

    local distro=$(detect_distro)
    echo ">>> Distribution détectée: ${distro}"

    case "${distro}" in
        arch)
            install_deps_arch
            ;;
        debian)
            install_deps_debian
            ;;
        *)
            echo "ERREUR: Distribution non supportée"
            echo "Supportées: Arch Linux, Debian/Ubuntu"
            exit 1
            ;;
    esac

    compile_basilisk
    copy_resources
    generate_config
    create_launcher
    setup_autostart

    echo
    echo "=============================================="
    echo "  Installation terminée !"
    echo "=============================================="
    echo
    echo "  Dossier:         ${INSTALL_DIR}"
    echo "  Lancer:          ${INSTALL_DIR}/run.sh"
    echo "  Dossier partagé: ${SHARED_DIR}"
    echo
    echo "  Tu peux aussi lancer depuis le menu applications"
    echo "  ou taper 'basilisk2' si ~/bin est dans ton PATH"
    if [ "${OPT_AUTOSTART}" = "true" ]; then
        echo
        echo "  Autostart activé: systemctl --user status basilisk2"
    fi
    echo
}

# Parse arguments et lance main
parse_args "$@"
main
