#!/bin/sh
SCRIPTPATH="`readlink -f "$0"`"
EPSXEPATH="`dirname "$SCRIPTPATH"`"
IMAGEPATH="`readlink -f "$1"`"

if [ "$#" = 0 -o ! -f "$IMAGEPATH" ]; then
	echo "Usage: $0 <gameimage> [options]"
	exit 1
fi
shift

echo "Using '$EPSXEPATH'..."

# disable core dumps
ulimit -c 0

# Figure out the game ID
GAMEID1="`head -c 65535 "$IMAGEPATH" | strings | grep '^PLAYSTATION                     ' | cut -b33- | sed 's/ *$//g'`"
GAMEID2="`head -c 65535 "$IMAGEPATH" | strings | grep '^[A-Z][A-Z][A-Z][A-Z]_[0-9][0-9][0-9].[0-9][0-9];' | cut -d';' -f1`"
# last resort
GAMEID3="`head -c 65535 "$IMAGEPATH" | sha1sum - | cut -d' ' -f1`"

GAMEID="`echo "${GAMEID1:-${GAMEID2:-$GAMEID3}}" | tr ' ' '_'`"

MC1="$EPSXEPATH/memcards/$GAMEID-card1.mcr"
MC2="$EPSXEPATH/memcards/$GAMEID-card2.mcr"

decomp_mc() {
	# Decompress memory card images
	if [ -f "$@" ]; then
		echo "$@ already exists, assuming it's newer."
	elif [ -f "$@.gz" ]; then
		echo "Decompressing $@.gz..."
		zcat "$@.gz" > "$@"
	fi
}

comp_mc() {
	# Compress memory card images
	if [ -f "$@" ]; then
		echo "Compressing $@..."
		gzip -9 -f "$@"
	fi
}

decomp_mc "$MC1"
decomp_mc "$MC2"

$EPSXEPATH/epsxe -subchan -slowboot -nogui -loadmemc0 "$MC1" -loadmemc1 "$MC2" -loadiso "$IMAGEPATH" "$@"

comp_mc "$MC1"
comp_mc "$MC2"
