#!/bin/bash
# A simple tool to prepend PS2 disc image file names with their appropriate gameids.
# This is just for OpenPS2Loader, and requires hdl-dump.

for disc_name in "$@"; do
    disc_path="$(realpath "$disc_name")"
    disc_dir="$(dirname "$disc_path")"
    disc_short="$(basename "$disc_path")"

    hdldump_output="$(hdl-dump cdvd_info "$disc_path" | cut -d ' ' -f 1)"
    gameid="${hdldump_output//\"/}"

    if ! echo "$disc_path" | grep -q "$gameid"; then
        new_disc_filename="${gameid}.${disc_short}"
        new_disc_path="${disc_dir}/${new_disc_filename}"

        echo "Previous path: ${disc_path}"
        echo "New path: ${new_disc_path}"
        mv "$disc_path" "$new_disc_path"
    else
        echo "${disc_short} is already named correctly."
    fi
done
