#!/bin/sh

if [ "$#" -ne 1 ]; then
	echo "Usage: apply_saturn.sh input.cue"
	exit 1
fi

cuename=$1
BASEDIR=`dirname "$0"`/
OUTDIR=`dirname "$cuename"`/
toolpath=$BASEDIR"tool/"
cdreplace=$toolpath"cd-replace/cd-replace"
cuetool=$toolpath"cuetool"
#You literally can't name the variable XDELTA or it fucks it up.
#Incredible software design, thank you.
xdeltapath=$toolpath"xdelta3-3_0_11/xdelta3-3.0.11-i686"

# The below is just to figure out the name of the bin and cue, basically.
# If you're looking at this file, you probably can just ignore
# this part and the path setup, and skip to #perform

workpath=$BASEDIR"work/"
patchpath=$BASEDIR"patches/"
mkdir -p $workpath
outname=$OUTDIR"RSG_EX_SAT"
outbinname=$outname".bin"
outcuename=$outname".cue"

binname=`$cuetool "$cuename"`

#perform
#We don't want to modify in-place, so make a copy to the output files
echo Copying disc image...
cp "$binname" "$outbinname"
cp "$cuename" "$outcuename"

echo Extracting game files...
"$cdreplace" -e "$binname" "SS\GAME.BIN" "$workpath""GAME.BIN"
"$cdreplace" -e "$binname" "SS\OPTION.BIN" "$workpath""OPTION.BIN"
"$cdreplace" -e "$binname" "SS\BACK_CHK.BIN" "$workpath""BACK_CHK.BIN"

echo Patching game files...
"$xdeltapath" -f -d -s "$workpath""GAME.BIN" "$patchpath""GAME.xdelta3" "$workpath""GAME.NEW.BIN"
"$xdeltapath" -f -d -s "$workpath""OPTION.BIN" "$patchpath""OPTION.xdelta3" "$workpath""OPTION.NEW.BIN"
"$xdeltapath" -f -d -s "$workpath""BACK_CHK.BIN" "$patchpath""BACK_CHK.xdelta3" "$workpath""BACK_CHK.NEW.BIN"

#Copy the patched files in
#SS=Saturn mode, STV=Arcade mode, yes they're supposed to be identical...
echo Inserting game files...
"$cdreplace" -r "$outbinname" "SS\GAME.BIN" "$workpath""GAME.NEW.BIN"
"$cdreplace" -r "$outbinname" "STV\GAME.BIN" "$workpath""GAME.NEW.BIN"
"$cdreplace" -r "$outbinname" "SS\OPTION.BIN" "$workpath""OPTION.NEW.BIN"
"$cdreplace" -r "$outbinname" "STV\OPTION.BIN" "$workpath""OPTION.NEW.BIN"
"$cdreplace" -r "$outbinname" "SS\BACK_CHK.BIN" "$workpath""BACK_CHK.NEW.BIN"

#Fix up the cue sheet; both timing and bin filename!
echo Fixing up cue sheet...
"$cuetool" "$outcuename" "$cuename" "$outbinname" "$binname"

echo Done!
