#!/bin/bash

SYSTEMS="apple2 arcade atari2600 atari7800 atarilynx coleco gamegear gb gba gbc mastersystem megadrive msx n64 nes ngpc pcengine sega32x sg1000 snes vectrex virtualboy wonderswan wonderswancolor"

# check if there is at least one parameter
if [ "$#" -ne 1 ]; then
    echo "You must enter a system name."
    echo "Supported systemas are:"
    for WORD in $SYSTEMS
    do
         echo -e "\t$WORD"
    done
    exit 0
fi

# check if the parameter is valid
if ! echo "$SYSTEMS" | grep -w "$1" > /dev/null; then
    echo "You must enter a valid system name."
    echo "Supported systemas are:"
    for WORD in $SYSTEMS
    do
         echo -e "\t$WORD"
    done
    exit 0
fi

readonly SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
readonly DATA_DIR="$SCRIPT_DIR/data"
readonly GAME_LIST_DIR="$SCRIPT_DIR/gamelists"
readonly HASCHEEVOS_TXT="${DATA_DIR}/$1_hascheevos.txt"
readonly HASHLIBRARY_JSON="${DATA_DIR}/$1_hashlibrary.json"
readonly BLUE_COLOR=$( tput setaf 4 ) ;
readonly RESET_COLOR=$( tput sgr0 ) ;

echo "Processing $1 system."
echo "Working folder: $GAME_LIST_DIR"

# extract hashes from files on data/system folder

# if file exists, delete it
if test -f "${HASCHEEVOS_TXT}"; then
    rm "${HASCHEEVOS_TXT}"
fi

# if file exists, delete it
if test -f "${HASHLIBRARY_JSON}"; then
    rm "${HASHLIBRARY_JSON}"
fi

# check if folder exists
if ! test -d "${GAME_LIST_DIR}/$1"; then
    echo "Folder ${GAME_LIST_DIR}/$1 does not exist."
    exit 0
fi

# create HASCHEEVOS_TXT file
grep -E "title=\"(.*?)\"" -Eo "${GAME_LIST_DIR}/$1/"* >> "${HASCHEEVOS_TXT}"
sed -i -E 's,^\/(.*?)g=,,g' "${HASCHEEVOS_TXT}"
sed -i -E 's,title=,true:,g' "${HASCHEEVOS_TXT}"
echo "File $HASCHEEVOS_TXT created."

# create HASHLIBRARY_JSON
echo "{" > "${HASHLIBRARY_JSON}"
echo "  \"Success\": true," >> "${HASHLIBRARY_JSON}"
echo "  \"MD5List\": {" >> "${HASHLIBRARY_JSON}"
for i in "${GAME_LIST_DIR}/$1/"*; do
    # catch hash and append to file
    printf "%s\n" "$(grep -E "[A-Fa-f0-9]{32}" -Ho "$i")" >> "${HASHLIBRARY_JSON}"
    printf "%s\r" "${BLUE_COLOR}Parsing $(basename "$i") ... ${RESET_COLOR}"
done
perl -i -pe 's/(^\/.*?=)([0-9]+):([0-9A-Za-z]{32})/    "$3": $2,/' "${HASHLIBRARY_JSON}"
echo "  }" >> "${HASHLIBRARY_JSON}"
echo "}" >> "${HASHLIBRARY_JSON}"
perl -i -00pe 's/,(?!.*,)//s' "${HASHLIBRARY_JSON}"
printf "%s\n" "Parsed $(wc -l < "${HASHLIBRARY_JSON}") hashes from $(find "${GAME_LIST_DIR}"/"$1" -type f | wc -l) games.                  "
echo "File: $HASHLIBRARY_JSON created."