#!/bin/bash

# Instala los programas necesarios
#sudo apt-get install -y mame-tools p7zip-full

## Comprueba los parametros
if [ "$#" -lt 2 ]; then
  printf "Uso: chd_from_zip.sh SOURCEDIR DESTDIR [-remove]\n"
  exit 0
else
  readonly sourcedir="$1"
  readonly destdir="$2"
fi

# Comprueba que exista el directorio de origen
if [ ! -d "$1" ]; then
  printf "El directorio %s no existe\n" "$1"
  exit 0
fi

# Colores
WHITE=$(tput setaf 7)
RED_BG=$(tput setab 1)
BLUE_BG=$(tput setab 4)
NORMAL=$(tput sgr0)
BOLD=$(tput bold)

# Procesa los ficheros
for zipfile in "${sourcedir}"/*.zip; do
  gameName="$(basename "$zipfile" .zip)"

  # Comprueba si existe ya el fichero antes de extraerlo
  if [ -f "${destdir}/${gameName}.chd" ]; then
    TEXT=">> ${gameName}.chd already exists"
    printf "%s\n" "${BOLD}${WHITE}${RED_BG}${TEXT}${NORMAL}"
  else
    TEXT=">> Extracting ${gameName}..."
    printf "\n%s\n" "${BOLD}${WHITE}${RED_BG}${TEXT}${NORMAL}"
    7z x "${zipfile}" -o"${destdir}/${gameName}-tmp"

    # Convierte a CHD
    TEXT=">> Converting ${gameName}..."
    printf "\n%s\n" "${BOLD}${WHITE}${RED_BG}${TEXT}${NORMAL}"
    find "${destdir}/${gameName}-tmp/" -type f -iname "*.cue" -exec chdman createcd -i {} -o "${destdir}/${gameName}.chd" \;

    # Borra el directorio temporal
    rm -rdf "${destdir}/${gameName}-tmp"
  fi

  # Elimina el fichero
  if [ "$3" = "-remove" ]; then
    rm "$zipfile"
  fi

  TEXT=">> ${gameName} completed !!!"
  printf "\n%s\n" "${BOLD}${WHITE}${BLUE_BG}${TEXT}${NORMAL}"

done

printf "All done.\n"
