#!/usr/bin/env bash
                                                                                                                                                                          

# Function to check if a file is an IWAD
is_iwad() {
    local file="$1"
    [[ "${file,,}" =~ ipk3$ ]] && return 0
    if [[ -f "$file" ]]; then
        # Extract the first four bytes and check if they match the IWAD signature
        if hexdump -n 4 -e '4/1 "%02X"' "$file" | grep -q '^49574144$'; then
            return 0
        else
            return 1
        fi
    fi
    return 1
}

iwad_menu() {
    # Extract the Path= lines from the [IWADSearch.Directories] section
    mapfile -t wadPaths < <(sed -n "/^\[IWADSearch.Directories\]/,/^\[/{/Path=/p;}" "$configFile" | cut -d '=' -f 2)
    declare -A uniqueWads
    for i in "${wadPaths[@]}"; do
        if [[ -d "$i" ]]; then
            while IFS= read -r -d $'\0' wad; do
                if is_iwad "$wad"; then
                    wad_name=$(basename "$wad")
                    uniqueWads["${wad_name,,}"]="$wad"
                fi
            done < <(find "$i" -follow -maxdepth 1 -type f \( -iname '*.wad' -o -iname '*.ipk3' \) -print0)
        fi
    done
    wadList=("${uniqueWads[@]}")
    # Set up the menu
    declare -a wadMenu
    for path in "${wadList[@]}" ; do
        title="${path##*/}"
        title="${title%.*}"
        wadMenu+=("${title}" "${path}")
    done
    # Run yad to display the dialog
    iwad=$(yad --list \
        --title="Yadoom" \
        --text="Select an Iwad" \
        --column="Iwad" \
        --column="Path" \
        --button="Launch:0" \
        --button="Close:1" \
        --hide-column=2 \
        --search-column=1 \
        --skip-taskbar \
        "${wadMenu[@]}")
    yadCode="$?"
    [[ ${yadCode} -eq 0 ]] || exit 0
    iwad="${iwad#*|}"
    iwad="${iwad%|}"
}
                                                                                                                                                                          
configFile="${XDG_CONFIG_HOME:-$HOME/.config}/gzdoom/gzdoom.ini"
declare -a gzdoomArgs

# Process arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        -c)
            configFile="$2"
            shift 2
            ;;
        -iwad|-i)
            iwad="$2"
            gzdoomArgs+=("-iwad" "$2")
            shift 2
            ;;
        *)
            gzdoomArgs+=("$1")
            shift
            ;;
    esac
done

# If no IWAD specified, show the menu
if [[ -z "$iwad" ]]; then
    iwad_menu
    gzdoomArgs+=("-iwad" "$iwad")
fi

# Launch GZDoom with all arguments
gzdoom "${gzdoomArgs[@]}"