#!/bin/bash

[  "$3" == "" ] && exec echo "Usage: $0 <ibackup Target> <restore_num> <action 1:restore, 2:restore&downlad>"

TARGET=$1
NUM=$2
ACTION=$3

CHECK_IBACKUP=$(ibackup list | awk 'NR > 1 { print $1 }' | egrep ${TARGET})
if [ -z "${CHECK_IBACKUP}" ]; then
	exec echo "${TARGET} is not existed in ibackup!"
else
	BACKUP_DATETIME=$($HOME/bin/ibackup list ${TARGET} | egrep "^${NUM}[[:space:]]+" | awk '{print $2}')
	BACKUP_DATETIME_NAME=$(echo ${BACKUP_DATETIME} | sed 's/[-:]//g')
	DIRECTORY_NAME="${TARGET}_${NUM}_${BACKUP_DATETIME_NAME}"
	OUTPUT_FILENAME="${TARGET}_${NUM}_${BACKUP_DATETIME_NAME}.zip"
	[ -d "/tmp/${DIRECTORY_NAME}" ] && rm -rf /tmp/${DIRECTORY_NAME}
	[ -f "~/www/download/${OUTPUT_FILENAME}" ] && rm -rf ~/www/download/localize_restore_dl/${OUTPUT_FILENAME}
fi

COUNTRY=$(echo ${TARGET} | awk -F"_" '{print $2}')
COUNTRY_UPPER=${COUNTRY^^}
EXTERNAL_IP_ADDR=$(curl icanhazip.com)

case ${COUNTRY_UPPER} in
	US)
		COUNTRY_UPPER_CHT="英文";;
	FR)
		COUNTRY_UPPER_CHT="法文";;
	DE)
		COUNTRY_UPPER_CHT="德文";;
	ES)
		COUNTRY_UPPER_CHT="西班牙文";;
	PT)
		COUNTRY_UPPER_CHT="葡萄牙文";;
	JP)
		COUNTRY_UPPER_CHT="日文";;
	CN)
		COUNTRY_UPPER_CHT="簡體中文";;
	*)
		COUNTRY_UPPER_CHT="未知語系";;
esac

MESSAGE_FILENAME="/tmp/restore_localization_${COUNTRY}_monitor.log"
[ -f "${MESSAGE_FILENAME}" ] && rm -rf ${MESSAGE_FILENAME}

yes | $HOME/bin/ibackup restore ${TARGET} /tmp/${DIRECTORY_NAME} ${NUM}

if [ "${ACTION}" == "2" ]; then
	cd /tmp/; zip ${OUTPUT_FILENAME} ${DIRECTORY_NAME}/T_*.ini ${DIRECTORY_NAME}/*GameDataTranslateFileList*
	cd /tmp/; cp -arf ${OUTPUT_FILENAME} ~/www/download/localize_restore_dl/.
	echo "翻譯還原資料下載\nDownload URL: http://${EXTERNAL_IP_ADDR}/download/localize_restore_dl/${OUTPUT_FILENAME}\n(連結不可直接點選 請複製後 貼到瀏覽器下載)" > ${MESSAGE_FILENAME}
	echo >> ${MESSAGE_FILENAME}
	cd /tmp/; unzip -l ${OUTPUT_FILENAME} >> ${MESSAGE_FILENAME}
	cd /tmp/; rm -rf ${OUTPUT_FILENAME}
	
	send_messages INFO restore_localization_${COUNTRY} "翻譯還原 ${COUNTRY_UPPER} ${COUNTRY_UPPER_CHT} 版號 ${NUM} 備份時間 ${BACKUP_DATETIME}"
fi
