#!/usr/bin/bash
#  ____  _   _                      
# / ___|| |_| |__   ___  _ __   ___ 
# \___ \| __| '_ \ / _ \| '_ \ / _ \
#  ___) | |_| | | | (_) | |_) |  __/
# |____/ \__|_| |_|\___/| .__/ \___|
#                       |_|         
#
# dolphin_gamecube.sh

GAMECUBE_FOLDER=$(dirname "$1")
DOLPHIN="flatpak run org.DolphinEmu.dolphin-emu -b -e"

filename=$(basename "$1")
extension="${filename##*.}"
ROM="${filename%.*}.iso"

# Check if 7z is installed
if ! which 7z &> /dev/null; then
    sudo apt install -y p7zip-full
fi

# Check if flatpak is installed
if ! which flatpak &> /dev/null; then
    sudo apt install -y flatpak gnome-software-plugin-flatpak
    flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
    flatpak install flathub
fi

# Check if Dolphin is installed
if ! flatpak list | grep -q org.DolphinEmu.dolphin-emu; then
    flatpak install org.DolphinEmu.dolphin-emu
fi

# If it is Zip/7z extract before running the Rom via Dolphin
if [[ $extension == "zip" || $extension == "7z" ]]; then
    # rm -rf $GAMECUBE_FOLDER/.tmp
    7z x "$1" -o$GAMECUBE_FOLDER/.tmp
    if [ $? -ne 0 ]; then
        echo "Extraction failed."
        exit 1
    fi
    $DOLPHIN "$GAMECUBE_FOLDER/.tmp/$ROM"

    # Delete extracted rom after playing
    rm -rf $GAMECUBE_FOLDER/.tmp

elif [[ $extension == "iso" || $extension == "rvz" ]]; then
    $DOLPHIN "$1"
else
    echo "ERROR: something is fucked"
fi