#!/bin/bash

sourcedir=$1
hashfile=$2
readonly SCRIPT_DIR="$(cd "$(dirname $0)" && pwd)"
systemfolder="$(basename "$2" .hashlist)"
tmpdir="$SCRIPT_DIR"/.tmpdir/
outputfile="$SCRIPT_DIR"/find_roms.log
outputdir=~/roms.retroachievements.2020/

# Ansi color code variables
red="\e[0;91m"
blue="\e[0;94m"
expand_bg="\e[K"
blue_bg="\e[0;104m${expand_bg}"
red_bg="\e[0;101m${expand_bg}"
green_bg="\e[0;102m${expand_bg}"
green="\e[0;92m"
white="\e[0;97m"
bold="\e[1m"
uline="\e[4m"
reset="\e[0m"

if test -d "$tmpdir"; then
    rm -rdf "$tmpdir"
    echo "Deleting $tmpdir folder."
fi
if ! test -d "$tmpdir"; then
    mkdir -p "$tmpdir"
    echo "Create $tmpdir folder."
fi
if test -f "$outputfile"; then
    rm "$outputfile"
fi
if ! test -d ${outputdir}"${systemfolder}"; then
    mkdir -p ${outputdir}"${systemfolder}"
    echo "Create ${outputdir}${systemfolder} folder."
fi

sleep 1

for zipfile in "${sourcedir}"/*.zip; do
  gameName="$(basename "$zipfile" .zip)"
  echo -e "${red}Extracting ${gameName}...${reset}"
  7z x "${zipfile}" -o${tmpdir}"${gameName}-tmp" > /dev/null
  for i in ${tmpdir}"${gameName}-tmp"/*; do
    hash=$(md5sum "$i" | grep -E "[0-9a-f]{32}" -Eo)
    if grep -q $hash "${hashfile}"; then
      echo "${gameName}" >> "${outputfile}"
      cp "${zipfile}" ${outputdir}"${systemfolder}"/ -v
    fi
  done
  rm -rdf ${tmpdir}/"${gameName}-tmp"
done

rm -rdf ${tmpdir}
chmod 755 ${outputdir}"${systemfolder}"/*
echo "$(find "${outputdir}"${systemfolder} -maxdepth 1 -type f | wc -l) files copied out of $(wc -l < $2) hashes"
