#!/bin/bash

# 載入 gamerc
source ~/.gamerc

# 抓取日期時間
DATETIME="$(/bin/date +%Y%m%dT%H%M)"

# 確認是每日檢查還是維護備份
if [ "$1" == "maintenance" ]; then
	COMMENT_TAG="[Maintenance Backup]"
else
	COMMENT_TAG="[Daily Backup]"
fi

# 確認翻譯檔目錄架構
TRANSLATE_NUM=$(cat ${HOME}/.gamerc | grep TRANSLATED_INI_UPLOAD_DIR_ | grep -v '#' | wc -l)

if [ "${TRANSLATE_NUM}" -gt 0 ]; then
	# 多國語系翻譯檔架構
	echo "1: Multi Lang"
	
	for multi_lang_directory in $(cat ${HOME}/.gamerc | grep TRANSLATED_INI_UPLOAD_DIR_ | grep -v '#' | awk -F"=" '{print $2}'); do
		LANG=$(echo ${multi_lang_directory} | sed 's/"//g' | awk -F"/" '{print $(NF-1)}' | awk -F"_" '{print $NF}')
		LANG_DIRECTORY=$(echo ${multi_lang_directory} | sed 's/"//g')
		echo "${LANG} => ${LANG_DIRECTORY}"

		# 舊檔案比對
		OLD_TRANSLATE_FILELIST="/tmp/md5_translate_${LANG}_list"

		if [ -f "${OLD_TRANSLATE_FILELIST}" ]; then
			# 舊檔案存在, 則進行比對
			MD5_OLD_TRANSLATE_FILELIST=$(cat ${OLD_TRANSLATE_FILELIST})
			MD5_CURRENT_TRANSLATE_FILELIST=$(md5sum ${LANG_DIRECTORY}/GameDataTranslateFileList_${LANG}.txt | awk -F' ' '{print $1}')

			if [ "${MD5_OLD_TRANSLATE_FILELIST}" != "${MD5_CURRENT_TRANSLATE_FILELIST}" ]; then
				# 比對備份有差異, 則進行備份
				ibackup backup translate_${LANG} "${LANG} => ${COMMENT_TAG} Restore to ${DATETIME}" 2>&1
			else
				echo "INFO: No new translate files ${LANG} need to backup." | colorize red black 
			fi
		else
			# 舊檔案不存在, 則直接備份
			ibackup backup translate_${LANG} "${LANG} => ${COMMENT_TAG} Restore to ${DATETIME}" 2>&1

			MD5_CURRENT_TRANSLATE_FILELIST=$(md5sum ${LANG_DIRECTORY}/GameDataTranslateFileList_${LANG}.txt | awk -F' ' '{print $1}')
		fi

		# 記錄此次翻譯檔清單的 MD5, 以供下此比對使用
		echo ${MD5_CURRENT_TRANSLATE_FILELIST} > ${OLD_TRANSLATE_FILELIST}
	done
else
	# 單一語系翻譯檔架構
	echo "2: Single Lang"

	single_lang_directory=$(cat ${HOME}/.gamerc | grep 'TRANSLATED_INI_UPLOAD_DIR='| awk -F"=" '{print $2}')
	LANG=$(cat ${HOME}/.gamerc | grep 'COUNTRY_CODE=' | sed 's/"//g' | awk -F"=" '{print $2}')
	LANG_DIRECTORY=$(echo ${single_lang_directory} | sed 's/"//g')
	echo "${LANG} => ${LANG_DIRECTORY}"

	# 舊檔案比對
	OLD_TRANSLATE_FILELIST="/tmp/md5_translate_list"
	
	if [ -f "${OLD_TRANSLATE_FILELIST}" ]; then
		# 舊檔案存在, 則進行比對
		MD5_OLD_TRANSLATE_FILELIST=$(cat ${OLD_TRANSLATE_FILELIST})
		MD5_CURRENT_TRANSLATE_FILELIST=$(md5sum ${LANG_DIRECTORY}/GameDataTranslateFileList.txt | awk -F' ' '{print $1}')

		if [ "${MD5_OLD_TRANSLATE_FILELIST}" != "${MD5_CURRENT_TRANSLATE_FILELIST}" ]; then
			# 比對備份有差異, 則進行備份
			ibackup backup translate "${LANG} => ${COMMENT_TAG} Restore to ${DATETIME}" 2>&1
		else
			echo "INFO: No new translate files ${LANGE} need to backup." | colorize red black 
		fi
	else
		# 舊檔案不存在, 則直接備份
		ibackup backup translate "${LANG} => ${COMMENT_TAG} Restore to ${DATETIME}" 2>&1

		MD5_CURRENT_TRANSLATE_FILELIST=$(md5sum ${LANG_DIRECTORY}/GameDataTranslateFileList.txt | awk -F' ' '{print $1}')
	fi

	# 記錄此次翻譯檔清單的 MD5, 以供下此比對使用
	echo ${MD5_CURRENT_TRANSLATE_FILELIST} > ${OLD_TRANSLATE_FILELIST}
fi
