#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2023 JELOS (https://github.com/JustEnoughLinuxOS)

LOGFILE="/var/log/migrate.log"

read -p "WARNING: This tool can cause data loss...  Make sure you have a backup before proceeding...  Press control-c now to cancel, or any other key to continue..."

for GAMES in /storage/games-internal /storage/games-external
do
  echo "Working on ${GAMES}..."
  if [ ! -d "${GAMES}/roms" ]
  then
    echo "Making ${GAMES}/roms..."
    mkdir -p "${GAMES}/roms" >>${LOGFILE} 2>&1 1|>>${LOGFILE}
  fi
  for DIR in $(find  "${GAMES}/" -type d -maxdepth 1 -mindepth 1 2>/dev/null)
  do
    TARGET_DIR=$(basename ${DIR})
    echo "Working on ${DIR}..."
    if [[ "${DIR}" =~ roms$ ]]
    then
      continue
    fi
    if [ ! -d "${GAMES}/roms/${TARGET_DIR}" ]
    then
      echo "Making ${GAMES}/roms/${TARGET_DIR}..."
      mkdir -p "${GAMES}/roms/${TARGET_DIR}" >>${LOGFILE} 2>&1
    fi
    mv "${DIR}"/* "${GAMES}/roms/${TARGET_DIR}" >>${LOGFILE} 2>&1
    rsync -av --remove-source-files "${DIR}"/* "${GAMES}/roms/${TARGET_DIR}" >>${LOGFILE} 2>&1
  done
  echo "Clean empties in ${GAMES}..."
  find "${GAMES}" -type d -empty -delete >>${LOGFILE} 2>&1 1|>>${LOGFILE}
  echo "Your games have been migrated, however you will need to manually clean up stale directories.  Please reboot your system now by running the `reboot` command."
done
