#!/bin/bash

MD5_VANILLA="7d96ffd6da21cc3f419e42f7227642fd"
MD5_FIRST63="50374bed7f84c51bdcdcefd6300ddb84"
MD5_LAST32="c5e46781d21cd4414e92d91502512500"

echo "Welcome to the Oni 2 (Angel Studios) Layout Patch Tool."

if [ -z "$1" ]; then
   echo "You need to pass me the path to your ISO of Oni 2. Exiting."
   exit
fi

if [ ! -f "$1" ]; then
   echo "Hmm, there doesn't seem to be any file at the path you passed me. Exiting."
   exit
fi

echo "Verifying checksum...."

MD5_INPUT=$(md5 "$1")
MD5_INPUT=${MD5_INPUT#*= }

if [ $MD5_INPUT != $MD5_VANILLA ]; then
   if [ $MD5_INPUT == $MD5_FIRST63 ]; then
      echo "This version is already patched to enabled the first 63 layouts! You should see them in the Load Game menu."
   elif [ $MD5_INPUT == $MD5_LAST32 ]; then
      echo "This version is already patched to enabled the last 32 layouts! You should see them in the Load Game menu."
   else
      echo "Unknown checksum! Sorry, this ISO isn't what I expected."
   fi

   echo "Exiting."
   exit
fi

echo "You have supplied an unmodified ISO of Oni 2. Do you wish to create a patched copy that enables the first 63 layouts or the last 32? Enter a number from this menu:" | fmt -w 80
echo "(1) First 63."
echo "(2) Last 32."
echo "(anything else) I changed my mind, please exit."
read the_answer
if [ -z "$the_answer" ]; then
   echo "No answer given, so I assume you changed your mind. Exiting."
   exit
elif [ "$the_answer" == "1" ]; then
   echo "Creating patched version..."
   ./xdelta3mac.exe -ds "$1" patchFromVanTo63.xd3 ./oni2dev_ps2_first63layouts.iso
   echo "Verifying checksum...."
   MD5_OUTPUT=$(md5 ./oni2dev_ps2_first63layouts.iso)
   MD5_OUTPUT=${MD5_OUTPUT#*= }
   if [ $MD5_OUTPUT != $MD5_FIRST63 ]; then
      echo "Uh-oh, something went wrong! Patch failed. Exiting."
      exit
   fi
elif [ "$the_answer" == "2" ]; then
   echo "Creating patched version..."
   ./xdelta3mac.exe -ds "$1" patchFromVanTo32.xd3 ./oni2dev_ps2_last32layouts.iso
   echo "Verifying checksum...."
   MD5_OUTPUT=$(md5 ./oni2dev_ps2_last32layouts.iso)
   MD5_OUTPUT=${MD5_OUTPUT#*= }
   if [ $MD5_OUTPUT != $MD5_LAST32 ]; then
      echo "Uh-oh, something went wrong! Patch failed. Exiting."
      exit
   fi
fi

echo "Goodbye."