#!/bin/bash
source $HOME/.gamerc

ENVIRONMENT_TEST="TEST"
ENVIRONMENT_LIVE="LIVE"
ENVIRONMENT_PREVIOUS="PREVIOUS"

### Backup Previous XignCode Version ###
ssh CTRL "if [ ! -d \"${XIGNCODE_PATCH_ROOT_CDN}${ENVIRONMENT_PREVIOUS}\" ]; then mkdir -p ${XIGNCODE_PATCH_ROOT_CDN}${ENVIRONMENT_PREVIOUS}; fi"
ssh CTRL "cd ${XIGNCODE_PATCH_ROOT_CDN}${ENVIRONMENT_PREVIOUS}; rm -rf ${XIGNCODE_PATCH_ROOT_DIRECTORY_NAME}; rsync -av --progress ${XIGNCODE_PATCH_ROOT_CDN}${ENVIRONMENT_LIVE}/* ${XIGNCODE_PATCH_ROOT_CDN}${ENVIRONMENT_PREVIOUS}/."

### Sync XignCode from TEST to LIVE in TEST Server ###
echo "[LOCAL] Sync Environment => ${XIGNCODE_PATCH_ROOT_SOURCE}${ENVIRONMENT_LIVE}/."

if [ ! -d "${XIGNCODE_PATCH_ROOT_SOURCE}${ENVIRONMENT_LIVE}/${XIGNCODE_PATCH_ROOT_DIRECTORY_NAME}" ]; then mkdir -p ${XIGNCODE_PATCH_ROOT_SOURCE}${ENVIRONMENT_LIVE}/${XIGNCODE_PATCH_ROOT_DIRECTORY_NAME}; chmod -R 777 ${XIGNCODE_PATCH_ROOT_SOURCE}${ENVIRONMENT_LIVE}/${XIGNCODE_PATCH_ROOT_DIRECTORY_NAME}; fi
rsync -av --delete --progress ${XIGNCODE_PATCH_ROOT_SOURCE}${ENVIRONMENT_TEST}/${XIGNCODE_PATCH_ROOT_DIRECTORY_NAME}/* ${XIGNCODE_PATCH_ROOT_SOURCE}${ENVIRONMENT_LIVE}/${XIGNCODE_PATCH_ROOT_DIRECTORY_NAME}/.

### Sync Patch Root Contents to XignCode CDN LIVE ###
echo "[REMOTE] Sync Environment => ${XIGNCODE_PATCH_ROOT_CDN}${ENVIRONMENT_LIVE}/."

rsync -av --delete --progress ${XIGNCODE_PATCH_ROOT_SOURCE}${ENVIRONMENT_LIVE}/${XIGNCODE_PATCH_ROOT_DIRECTORY_NAME} ${XIGNCODE_PATCH_ROOT_CDN_MACHINE}:${XIGNCODE_PATCH_ROOT_CDN}${ENVIRONMENT_LIVE}/.

cd ~/patch/; php flush.php flush_all.txt

### XignCode Update Info to ChatBot ###
XIGNCODE_VERSION=$(basename ${XIGNCODE_PATCH_ROOT_SOURCE}${ENVIRONMENT_LIVE}/${XIGNCODE_PATCH_ROOT_DIRECTORY_NAME}/List64/[0-9]*)
output_filename="/tmp/xigncode_live_cdn_monitor.log"
echo "XignCode PatchRoot ( Rev. ${XIGNCODE_VERSION} ) 已上正式 CDN，可以測試囉!" > $output_filename
send_messages_with_pic INFO xigncode_live_cdn "XignCode 版本更新"
