#!/bin/bash

BASEDIR="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 || exit ; pwd -P )"
readonly BASEDIR
readonly SOURCE=~/roms/filtered
C_BLUE=$(tput setaf 4)
readonly C_BLUE
C_NORMAL=$(tput sgr0)
readonly C_NORMAL

## Elimina los directorios
printf "%s\n" "${C_BLUE}elimina los directorios ...${C_NORMAL}"
rm "${BASEDIR}"/bios
rm -rdf "${BASEDIR}"/images
rm -rdf "${BASEDIR}"/videos
rm -rdf "${BASEDIR}"/roms

## Crea los directorios
printf "%s\n" "${C_BLUE}crea los directorios ...${C_NORMAL}"
ln -sv ~/roms/bios/retroarch "${BASEDIR}"/bios
mkdir -pv "${BASEDIR}"/roms/arcade/lr-fbneo
mkdir -pv "${BASEDIR}"/images
mkdir -pv "${BASEDIR}"/videos

## Añade los enlaces a las roms
printf "\n%s\n" "${C_BLUE}añade los enlaces a las roms de consola ...${C_NORMAL}"
~/roms/packs/create_rom_pack.sh ${SOURCE} "${BASEDIR}"/roms console

printf "\n%s\n" "${C_BLUE}añade los enlaces a los juegos de cd ...${C_NORMAL}"
~/roms/packs/create_rom_pack.sh ${SOURCE} "${BASEDIR}"/roms cd_system

## Elimina los sistemas que sobran
printf "\n%s\n" "${C_BLUE}elimina las carpetas que sobran ...${C_NORMAL}"
rm -rdfv "${BASEDIR}"/roms/dreamcast
rm -rdfv "${BASEDIR}"/roms/psp
rm -rdfv "${BASEDIR}"/roms/saturn

## Copia las roms de arcade
printf "\n%s\n" "${C_BLUE}añade las roms de cps1 ...${C_NORMAL}"
cp -v ${SOURCE}/cps1/*.zip "${BASEDIR}"/roms/arcade/lr-fbneo

printf "\n%s\n" "${C_BLUE}añade las roms de cps2 ...${C_NORMAL}"
cp -v ${SOURCE}/cps2/*.zip "${BASEDIR}"/roms/arcade/lr-fbneo

## Escanea las roms para añadir las imagenes y videos
printf "\n%s\n" "${C_BLUE}escanea las roms para añadir imagenes y videos ...${C_NORMAL}"
~/code/bashscript/skyscraper.sh build emulationstation "${BASEDIR}"/roms 

## Mueve las imagenes y los videos a sus respectivas carpetas
printf "\n%s\n" "${C_BLUE}mueve las imagenes y los videos a sus respectivas carpetas ...${C_NORMAL}"
for SYSTEM in $(find ./roms -maxdepth 1 -mindepth 1 -type d -exec basename {} \;); do
	printf "%s\n" "procesando las imagenes y videos de ${C_BLUE}${SYSTEM}${C_NORMAL} ..."
	if [ -d "${BASEDIR}"/roms/"${SYSTEM}"/media/ ]
	then
		mv "${BASEDIR}"/roms/"${SYSTEM}"/media/screenshots "${BASEDIR}"/images/"${SYSTEM}"
		mv "${BASEDIR}"/roms/"${SYSTEM}"/media/videos "${BASEDIR}"/videos/"${SYSTEM}"
		rm -rdf "${BASEDIR}"/roms/"${SYSTEM}"/media
	fi
done
if [ -d "${BASEDIR}"/images/arcade ]
then
	mkdir -p "${BASEDIR}"/images/arcade/lr-fbneo
	mv "${BASEDIR}"/images/arcade/*.png "${BASEDIR}"/images/arcade/lr-fbneo
fi

## Elimina los ficheros gamelist.xml
printf "\n%s\n" "${C_BLUE}elimina los ficheros gamelist.xml ...${C_NORMAL}"
find "${BASEDIR}" -type f -iname "gamelist.xml" -exec rm -v {} \;