#!/bin/bash

# Automatic Casio SDK installation script
set -e  # Exit immediately on error

# Function to install dependencies
install_dependencies() {
    echo "Installing dependencies..."
    sudo apt update
    sudo apt upgrade -y
    sudo apt install -y cmake zlib1g-dev libpng-dev wget tar
}

# Function to get username
get_username() {
    if [ -n "$SUDO_USER" ]; then
        echo "$SUDO_USER"
    else
        echo "$(whoami)"
    fi
}

# Function to change to home directory if needed
ensure_home_directory() {
    current_dir=$(pwd)
    home_dir=$(eval echo ~$USERNAME)
    
    if [ "$current_dir" != "$home_dir" ]; then
        echo "WARNING: Script should be run from home directory ($home_dir)"
        echo "Current directory: $current_dir"
        echo "Changing to home directory..."
        cd "$home_dir"
        echo "Now in: $(pwd) ✓"
    else
        echo "Current directory: $(pwd) ✓"
    fi
}

# Function to add to PATH and verify
setup_path() {
    local username=$1
    local path_line='export PATH="/home/'"$username"'/opt/sh3eb-elf/bin:$PATH"'
    
    # Check if already added to avoid duplicates
    if ! grep -q "sh3eb-elf/bin" ~/.bashrc; then
        echo "$path_line" >> ~/.bashrc
        echo "PATH added to ~/.bashrc"
    else
        echo "PATH already configured in ~/.bashrc"
    fi
    
    # Add to current session PATH temporarily for the script
    export PATH="/home/$username/opt/sh3eb-elf/bin:$PATH"
    echo "Temporarily added to current session PATH"
}

# Function to verify toolchain installation
verify_toolchain() {
    echo "Verifying toolchain installation..."
    
    # Check if toolchain directory exists
    if [ -d "/home/$USERNAME/opt/sh3eb-elf/bin" ]; then
        echo "Toolchain directory found ✓"
    else
        echo "ERROR: Toolchain directory not found at /home/$USERNAME/opt/sh3eb-elf/bin"
        echo "Please check the casiolocal installation and try again."
        exit 1
    fi
    
    # Check if sh3eb-elf-gcc is accessible
    if command -v sh3eb-elf-gcc >/dev/null 2>&1; then
        echo "Toolchain is accessible ✓"
        echo "Toolchain version:"
        sh3eb-elf-gcc --version
    else
        echo "ERROR: sh3eb-elf-gcc not found in PATH"
        echo "Please restart your terminal and run the script again."
        exit 1
    fi
}

# Function to handle Makefile modification
handle_makefile() {
    local username=$1
    
    echo ""
    echo "=== Makefile Configuration ==="
    echo "The Makefile contains commands that require Wine for emulator support."
    echo "If you don't have Wine installed or don't plan to use the emulator,"
    echo "these commands will cause errors during compilation."
    echo ""
    
    # Create backup of original Makefile
    if [ -f "Makefile" ]; then
        cp Makefile Makefile.backup
        echo "Backup created: Makefile.backup"
    fi
    
    # Ask user for preference
    read -p "Do you want to remove Wine-related commands from Makefile? (y/N): " choice
    case "$choice" in
        y|Y|yes|YES)
            echo "Removing Wine-related commands from Makefile..."
            sed -i "s/parisse/$username/g" Makefile
            sed -i '/\/bin\/cp/d;/\.wine\/drive_c/d' Makefile
            echo "Makefile modified successfully ✓"
            ;;
        *)
            echo "Keeping Wine commands in Makefile."
            echo "NOTE: If you don't have Wine installed, the 'make' command may fail."
            sed -i "s/parisse/$username/g" Makefile
            ;;
    esac
    
    echo ""
    echo "You can always restore the original Makefile by running:"
    echo "  cp Makefile.backup Makefile"
    echo "Or modify it manually if you install Wine later."
}

# Main function
main() {
    echo "=== Casio SDK Automatic Installation Script ==="
    
    # Get username
    USERNAME=$(get_username)
    echo "Detected username: $USERNAME"
    
    # Ensure we're in home directory
    ensure_home_directory
    
    # Install dependencies
    install_dependencies
    
    # Download and install libmpfr.so.4
    echo "Installing libmpfr.so.4..."
    wget https://www-fourier.univ-grenoble-alpes.fr/~parisse/casio/libmpfr.so.4
    sudo cp libmpfr.so.4 /usr/local/lib/
    echo "/usr/local/lib" | sudo tee -a /etc/ld.so.conf
    sudo ldconfig
    rm -f libmpfr.so.4
    
    # Download and extract casiolocal
    echo "Installing casiolocal..."
    wget https://www-fourier.univ-grenoble-alpes.fr/~parisse/casio/casiolocal.tgz
    tar xzf casiolocal.tgz
    rm -f casiolocal.tgz
    
    # Configure PATH
    setup_path "$USERNAME"
    
    # Verify toolchain installation
    verify_toolchain
    
    # Download and install mkg3a
    echo "Installing mkg3a..."
    wget https://www-fourier.ujf-grenoble.fr/~parisse/casio/mkg3a.tgz
    tar xzf mkg3a.tgz
    cd mkg3a
    cd build
    cmake ..
    make
    sudo make install
    cd ../..
    rm -rf mkg3a mkg3a.tgz
    
    # Download and install libfxcg
    echo "Installing libfxcg..."
    wget https://www-fourier.ujf-grenoble.fr/~parisse/casio/libfxcg.tgz
    tar xzf libfxcg.tgz
    cd libfxcg
    make install 
    cd ..
    rm -rf libfxcg libfxcg.tgz
    
    # Download and install giacbf
    echo "Installing giacbf..."
    wget https://www-fourier.ujf-grenoble.fr/~parisse/casio/giacbf.tgz
    tar xzf giacbf.tgz
    cd giacbf
    
    # Handle Makefile configuration
    handle_makefile "$USERNAME"
    
    # Final compilation
    echo "Starting final compilation (this may take several minutes)..."
    make
    
    echo ""
    echo "=== Compilation completed successfully! ==="
    echo ""
    echo "IMPORTANT: If any errors occurred during compilation and you"
    echo "want to try to recompile it you must:"
    echo ""
    echo "1. Restart your terminal and browse to the source code folder"
    echo "OR, if you want to keep the current terminal"
    echo "2. Run: source ~/.bashrc"
    echo ""
    echo "If you install Wine later for emulator support, you can restore"
    echo "the original Makefile with: cp Makefile.backup Makefile"
}

# Execute the script
main "$@"
