#!/bin/bash
source $HOME/.gamerc
[ "$2" == "" ] && exec echo "Usage: $0 <MERGE_DIRECOTRY> <PATCH_VERSION_1> <PATCH_VERSION_2> ..."

PATCH_ROOT_DIRECTORY="$HOME/patch"
MERGE_DIRECTORY="$1"
TEMP_MERGE_DIRECTORY="${PATCH_ROOT_DIRECTORY}/${MERGE_DIRECTORY}"
ARGUMENTS_CNT="$#"

rm -rf ${TEMP_MERGE_DIRECTORY}
mkdir -p ${TEMP_MERGE_DIRECTORY}

for directory in $(seq 2 ${ARGUMENTS_CNT}); do
	patch=$(eval "echo \${$directory}")

	PATCH_DIRECTORY="$PATCH_ROOT_DIRECTORY/$patch"
	if [ ! -d "${PATCH_DIRECTORY}" ]; then
		exec echo "ERROR: Wrong patch version name ($patch) for directory, please check it again."
	else
		if [ "$GAME_TYPE" == "DJ" ]; then
			EXTENSION="TAR"
			CLIENT_PATCH_DIRECTORY=$(basename ${PATCH_DIRECTORY}/*.${EXTENSION} | sed "s/.${EXTENSION}/bz2/")
			CLIENT_PATCH_TARBALL=$(basename ${PATCH_DIRECTORY}/*.${EXTENSION})
			FILELIST="GameDataFileList.txt.bz2"
		elif [ "$GAME_TYPE" == "FF" ]; then
			EXTENSION="tar"
			CLIENT_PATCH_DIRECTORY=$(basename ${PATCH_DIRECTORY}/*.${EXTENSION} | sed "s/.${EXTENSION}//")
			CLIENT_PATCH_TARBALL=$(basename ${PATCH_DIRECTORY}/*.${EXTENSION})
			FILELIST="_GameDataFileList.txt"
		fi

		if [ -f ${PATCH_DIRECTORY}/${CLIENT_PATCH_TARBALL} ]; then
			tar xf ${PATCH_DIRECTORY}/${CLIENT_PATCH_TARBALL} -C $TEMP_MERGE_DIRECTORY
			mv $TEMP_MERGE_DIRECTORY/$CLIENT_PATCH_DIRECTORY/* $TEMP_MERGE_DIRECTORY/
			rmdir $TEMP_MERGE_DIRECTORY/$CLIENT_PATCH_DIRECTORY
		else
			exec echo "ERROR: No ingame client patch tarball, please check it again."
		fi
	fi
done

cd $TEMP_MERGE_DIRECTORY
DATETIME="$(/bin/date +%Y%m%d%H%M%S)"
MERGE_CLIENT_PATCH_DIRECTORY="${DATETIME}bz2"
if [ "$GAME_TYPE" == "DJ" ]; then
	MERGE_CLIENT_PATCH_TARBALL="${DATETIME}.${EXTENSION}"
elif [ "$GAME_TYPE" == "FF" ]; then
	MERGE_CLIENT_PATCH_TARBALL="${DATETIME}bz2.${EXTENSION}"
fi
mkdir -p $MERGE_CLIENT_PATCH_DIRECTORY
mv * $MERGE_CLIENT_PATCH_DIRECTORY
tar cvzf $MERGE_CLIENT_PATCH_TARBALL $MERGE_CLIENT_PATCH_DIRECTORY
rm -rf $MERGE_CLIENT_PATCH_DIRECTORY
