#!/bin/bash

###### 檔案資訊 ######
#
# 檔名: remote_backup_db_gcp <抓取離今天過往哪天的備份DB/all(全部)> <local/gcp/all>
#
# 功能: 將所有 LIVE DB 備份至 GCP Cloud Storage.
#	包含 local: FROM LIVE DB to CTRL.
#	以及 gcp: FROM CTRL to GCP.       
#
# 前置作業: 1. 建議在 CTRL 機上佈署中介環境, 且 CTRL 必須開通 Cloud Storage "讀/寫" 的權限
#           2. Cloud Storage 請先確認上傳的 Bucket Path, 並設定在 gamerc 或是此腳本的參數中
#
###### 檔案資訊 ######

[ "$2" == "" ] && exec echo "Usage: $0 <previous day numbers (-1,-2,-3,...,-7,-30,...)/all> <local/gcp/all>"

# 如果 gamerc 存在, 則載入它
[ -f ~/.gamerc ] && source ~/.gamerc

# 檢查執行機器是否在 CTRL 機上
[ -f ~/.gamerc ] && egrep -q "CTRL" <<< "$HOST_NAME" || exec echo "Error: $(basename $0) can only run on CTRL server."

# 如果是非 Ctrl 架構請自行設定遊戲名稱跟國家名稱
[ -z "${GAME_TYPE}" ] && GAME_TYPE="非Ctrl架構, 自行設定"

# GCP 備份目錄
[ -z "${GCP_DBBACKUP_DIR}" ] && GCP_DBBACKUP_DIR="非Ctrl架構, 請自行設定"
[ "${GCP_DBBACKUP_DIR}" == "非Ctrl架構, 自行設定" ] && exec echo "Please set up the variable 'GCP_DBBACKUP_DIR' first."
[ ! -d  "${GCP_DBBACKUP_DIR}" ] && mkdir -p ${GCP_DBBACKUP_DIR}
[ ! -d  "${GCP_DBBACKUP_DIR}_OLD" ] && mkdir -p ${GCP_DBBACKUP_DIR}_OLD
[ -z "${CTRL_DBBACKUP_CUR_RESERVED_DAYS}" ] && CTRL_DBBACKUP_CUR_RESERVED_DAYS="7"
[ -z "${CTRL_DBBACKUP_OLD_RESERVED_DAYS}" ] && CTRL_DBBACKUP_OLD_RESERVED_DAYS="14"

# 同步資料庫檔案的備份日期
[ "${GAME_TYPE}" == "非Ctrl架構, 自行設定" ] && exec echo "Please set up the variable 'GAME_TYPE' first."
RSYNC_DAYS=$1
[ "${RSYNC_DAYS}" == "all" ] && FILENAME_PATTERN="${GAME_TYPE}*.sql" || FETCH_DATE=$(date +%Y%m%d -d "${RSYNC_DAYS} days"); FILENAME_PATTERN="${GAME_TYPE}*${FETCH_DATE}*.sql"

# 同步方式
RSYNC_METHOD=$2

# GCP Storage Bucket Path
[ -z "${GCP_BUCKET_PATH}" ] && GCP_BUCKET_PATH="非Ctrl架構, 請自行設定"
[ "${GCP_BUCKET_PATH}" == "非Ctrl架構, 自行設定" ] && exec echo "Please set up the variable 'GCP_BUCKET_PATH' first."

# 本地端同步: LIVE => CTRL
if [ "${RSYNC_METHOD}" == "local" -o "${RSYNC_METHOD}" == "all" ]; then
	echo "1. Sync Database From LIVE DB to CTRL"

	# 抓取營運中的 GAMEDB 列表
	GAMEDB_LISTS=$(psql -U postgres WebTool -c "COPY ( SELECT set_id FROM db_setup WHERE is_commercial = 1 AND set_id = 2 ORDER BY set_id ) TO STDOUT CSV")
	for set in ${GAMEDB_LISTS}; do
		echo GAMEDB${set} | colorize yellow black
		# 抓取 GAMEDB 資料庫備份
		ssh GAMEDB${set} "rsync -avz ${HOME}/DBbackup/${FILENAME_PATTERN} CTRL:${GCP_DBBACKUP_DIR}/"

	done
fi

# 雲端同步: CTRL => GCP Storage
if [ "${RSYNC_METHOD}" == "gcp" -o "${RSYNC_METHOD}" == "all" ]; then
	echo "2. Sync Database From CTRL to Google Cloud Storage"

	cd ${GCP_DBBACKUP_DIR}
	gsutil -m cp ${FILENAME_PATTERN} gs://${GCP_BUCKET_PATH}
fi
