#!/bin/bash
[ "$4" == "" ] && exec echo "Usage: $0 
P1: <ACTION>

create_table_if_not_exist <DBNAME>
backup <DBNAME> <FILENAME_FULL>
file_modification <FILENAME_FULL>
add_info <FILENAME_FULL> <NOTE>
import_csv <DBNAME> <FILENAME_FULL> <NOTE>
db_modification <DBNAME>
output <DBNAME>
restore <DBNAME> <FILENAME_FULL>

prepare => create_table_if_not_exist + backup + file_modification + add_info + import_csv
execute => db_modification + output
all => prepare + execute

backup => backup_file + backup_db
db_modification => update_current_bonus_2log + update_modified_bonus_2log + update_online_bonus_2tbuser + update_checked_bonus_2log + update_date_status_2log
add_info => add_regdate + add_note + add_status
output => output_stdout + output_csv

restore => restore_file + restore_db

P2: <DBNAME> 
P3: <FILENAME with full path> 
P4: <NOTE>"

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

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

ACTION=$1
DBNAME=$2
FILENAME_FULL=$3
NOTE=$4
FILENAME_BASE=$(basename $3)
GAME_TYPE_LOWER="${GAME_TYPE,,}"
COUNTRY_CODE_LOWER="${COUNTRY_CODE,,}"
LOG_TABLE_NAME="z_comp_${GAME_TYPE_LOWER}${COUNTRY_CODE_LOWER}_bonus_log"

echo "Initialize: ${ACTION} ${DBNAME} ${FILENAME_FULL} ${NOTE} ${FILENAME_BASE}"

function create_table_if_not_exist() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	echo "Create Log Table Exist if not exist: ${DBNAME} ( Log Table: ${TABLENAME} )"
	psql -U postgres ${DBNAME} -c "CREATE TABLE IF NOT EXISTS ${TABLENAME} (xluser_id text, current_bonus integer, add_bonus integer, modified_bonus integer, regdate timestamp with time zone, modified_date timestamp with time zone, note text, status integer, checked_bonus integer);"
}

function backup_file() {
	FILENAME_FULL=$1
	if [ ! -f "${FILENAME_FULL}" ]; then
		exec echo "${FILENAME_FULL} is not exist!"
	fi

	echo "Backup: ${FILENAME_FULL}"
	BACKUP_FILENAME="${FILENAME_FULL}.bak"
	if [ ! -f "${BACKUP_FILENAME}" ]; then
		cp -arf ${FILENAME_FULL} ${BACKUP_FILENAME}
	else
		rm -rf ${FILENAME_FULL}
		cp -arf ${BACKUP_FILENAME} ${FILENAME_FULL}
	fi

	ls -hltra ${FILENAME_FULL} ${BACKUP_FILENAME}
}

function backup_db() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	OUTPUT_DATE=$(date +"%Y%m%d")
	BACKUP_DB_FILE="/tmp/${TABLENAME}_${OUTPUT_DATE}_backup.sql"
	echo "Backup DB: ${DBNAME} ( Table: ${TABLENAME} ) => ${BACKUP_DB_FILE}"
	pg_dump -U postgres ${DBNAME} -t ${TABLENAME} > ${BACKUP_DB_FILE}
}

function file_modification() {
	FILENAME_FULL=$1
	if [ -f "${FILENAME_FULL}" ]; then
		chmod 644 ${FILENAME_FULL}; dos2unix ${FILENAME_FULL}
		echo "" >> ${FILENAME_FULL}
		sed -i '/^$/d' ${FILENAME_FULL}
		echo "File Modification: ${FILENAME_FULL}"
	else
		exec echo "${FILENAME_FULL} is not exist!"
	fi
}

function add_regdate() {
	FILENAME_FULL=$1
	echo "Add Regdate: now()"
	sed -i "s/\$/,now()/g" ${FILENAME_FULL}
}

function add_note() {
	FILENAME_FULL=$1
	NOTE=$2
	echo "Add Note: ${NOTE}"
	sed -i "s/\$/,${NOTE}/g" ${FILENAME_FULL}
}

function add_status() {
	FILENAME_FULL=$1
	STATUS="0"
	echo "Add Status: ${STATUS}"
	sed -i "s/\$/,${STATUS}/g" ${FILENAME_FULL}
}

function import_csv() {
	DBNAME=$1
	FILENAME_FULL=$2
	NOTE=$3
	TABLENAME=${LOG_TABLE_NAME}
	echo "Import CSV: ${DBNAME} ${NOTE} ( Log Table: ${TABLENAME} )"
	psql -U postgres ${DBNAME} -c "COPY ${TABLENAME} (xluser_id, add_bonus, regdate, note, status) FROM '${FILENAME_FULL}' CSV;"
	output_stdout ${DBNAME}
}

function update_current_bonus_2log() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	echo "Update Current Bonus: ${DBNAME} ( Log Table: ${TABLENAME} )"
	psql -U postgres ${DBNAME} -c "UPDATE ${TABLENAME} SET current_bonus = bonus FROM tb_user WHERE ${TABLENAME}.xluser_id = tb_user.mid AND ${TABLENAME}.status = 0;"
}

function update_modified_bonus_2log() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	echo "Update Modified Bonus: ${DBNAME} ( Log Table: ${TABLENAME} )"
	psql -U postgres ${DBNAME} -c "UPDATE ${TABLENAME} SET modified_bonus = current_bonus + add_bonus WHERE status = 0;"
}

function update_online_bonus_2tbuser() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	echo "Update Online Bonus: ${DBNAME} ( Online Table: tb_user )"
	psql -U postgres ${DBNAME} -c "UPDATE tb_user SET bonus = modified_bonus FROM ${TABLENAME} WHERE tb_user.mid = ${TABLENAME}.xluser_id AND ${TABLENAME}.status = 0;"
}

function update_checked_bonus_2log() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	echo "Update Checked Bonus: ${DBNAME} ( Log Table: ${TABLENAME} )"
	psql -U postgres ${DBNAME} -c "UPDATE ${TABLENAME} SET checked_bonus = bonus FROM tb_user WHERE ${TABLENAME}.xluser_id = tb_user.mid AND ${TABLENAME}.status = 0;"
}

function update_date_status_2log() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	echo "Update Modified Date & Status: ${DBNAME} ( Log Table: ${TABLENAME} )"
	psql -U postgres ${DBNAME} -c "UPDATE ${TABLENAME} SET modified_date = now(), status = 1 WHERE status = 0 AND modified_bonus = checked_bonus;"
}

function output_original_file() {
	FILENAME_FULL=$1
	echo "Output Original File => ${FILENAME_FULL}"
	cat ${FILENAME_FULL}
}

function output_stdout() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	CURRENT_DATE=$(date +"%Y-%m-%d")
	echo "Output To Stdout: ${DBNAME} ( Log Table: ${TABLENAME} )"
	psql -U postgres ${DBNAME} -c "SELECT * FROM ${TABLENAME} WHERE regdate >= '${CURRENT_DATE}' ORDER BY modified_bonus;"
}

function output_csv() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	CURRENT_DATE=$(date +"%Y-%m-%d")
	OUTPUT_DATE=$(date +"%Y%m%d")
	echo "Output CSV: ${DBNAME} ( Log Table: ${TABLENAME} ) => /tmp/${TABLENAME}_${OUTPUT_DATE}.csv"
	psql -U postgres ${DBNAME} -c "COPY (SELECT * FROM ${TABLENAME} WHERE regdate >= '${CURRENT_DATE}' ORDER BY modified_bonus) TO '/tmp/${TABLENAME}_${OUTPUT_DATE}.csv' HEADER CSV;"
}

function restore_file() {
	FILENAME_FULL=$1

	echo "Restore: ${FILENAME_FULL}"
	RESTORE_FILENAME="${FILENAME_FULL}.bak"
	if [ ! -f "${RESTORE_FILENAME}" ]; then
		exec echo "${RESTORE_FILENAME} is not exist!"
	else
		rm -rf ${FILENAME_FULL}
		mv ${RESTORE_FILENAME} ${FILENAME_FULL}
	fi

	ls -hltra ${FILENAME_FULL}
}

function restore_db() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	CURRENT_DATE=$(date +"%Y-%m-%d")
	OUTPUT_DATE=$(date +"%Y%m%d")
	RESTORE_DB_FILE="/tmp/${TABLENAME}_${OUTPUT_DATE}_backup.sql"
	psql -U postgres ${DBNAME} -c "UPDATE tb_user SET bonus = current_bonus FROM ${TABLENAME} WHERE tb_user.mid = ${TABLENAME}.xluser_id AND modified_date >= '${CURRENT_DATE}';"
	if [ -f "${RESTORE_DB_FILE}" ]; then
		echo "Restore DB: ${DBNAME} ( Table: ${TABLENAME} )"
		psql -U postgres ${DBNAME} -c "DROP TABLE ${TABLENAME};"
		psql -U postgres ${DBNAME} -c "\i ${RESTORE_DB_FILE}"
	fi
}

function output_stdout_tbuser() {
	DBNAME=$1
	TABLENAME=${LOG_TABLE_NAME}
	CURRENT_DATE=$(date +"%Y-%m-%d")
	echo "Output To Stdout: ${DBNAME} ( Online Table: tb_user )"
	psql -U postgres ${DBNAME} -c "SELECT idnum, mid, pvalues, bonus FROM tb_user WHERE mid IN (SELECT xluser_id FROM ${TABLENAME} WHERE regdate >= '${CURRENT_DATE}') ORDER BY bonus;"
}

function backup() {
	DBNAME=$1
	FILENAME_FULL=$2

	backup_file ${FILENAME_FULL}
	backup_db ${DBNAME}
}

function restore() {
	DBNAME=$1
	FILENAME_FULL=$2

	restore_file ${FILENAME_FULL}
	restore_db ${DBNAME}
}

function add_info() {
	FILENAME_FULL=$1
	NOTE=$2

	add_regdate ${FILENAME_FULL}
	add_note ${FILENAME_FULL} ${NOTE}
	add_status ${FILENAME_FULL}
}

function db_modification() {
	DBNAME=$1

	update_current_bonus_2log ${DBNAME}
	update_modified_bonus_2log ${DBNAME}
	update_online_bonus_2tbuser ${DBNAME}
	update_checked_bonus_2log ${DBNAME}
	update_date_status_2log ${DBNAME}
	output_stdout ${DBNAME}
}

function output() {
	DBNAME=$1

	output_stdout ${DBNAME}
	output_csv ${DBNAME}
}

function prepare() {
	DBNAME=$1
	FILENAME_FULL=$2
	NOTE=$3

	create_table_if_not_exist ${DBNAME}
	backup ${DBNAME} ${FILENAME_FULL}
	file_modification ${FILENAME_FULL}
	add_info ${FILENAME_FULL} ${NOTE}
	output_original_file ${FILENAME_FULL}
	import_csv ${DBNAME} ${FILENAME_FULL} ${NOTE}
}

function execute() {
	DBNAME=$1
	FILENAME_FULL=$2
	NOTE=$3

	db_modification ${DBNAME}
	output ${DBNAME}
}

function all() {
	DBNAME=$1
	FILENAME_FULL=$2
	NOTE=$3

	prepare ${DBNAME} ${FILENAME_FULL} ${NOTE}
	execute ${DBNAME} ${FILENAME_FULL} ${NOTE}
}

if [ "${ACTION}" == "create_table_if_not_exist" ]; then
	create_table_if_not_exist ${DBNAME}
elif [ "${ACTION}" == "backup" ]; then
	backup ${DBNAME} ${FILENAME_FULL}
elif [ "${ACTION}" == "backup_file" ]; then
	backup_file ${FILENAME_FULL}
elif [ "${ACTION}" == "backup_db" ]; then
	backup_db ${DBNAME}
elif [ "${ACTION}" == "file_modification" ]; then
	file_modification ${FILENAME_FULL}
elif [ "${ACTION}" == "add_info" ]; then
	add_info ${FILENAME_FULL} ${NOTE}
elif [ "${ACTION}" == "add_note" ]; then
	add_note ${FILENAME_FULL} ${NOTE}
elif [ "${ACTION}" == "add_status" ]; then
	add_status ${FILENAME_FULL}
elif [ "${ACTION}" == "import_csv" ]; then
	import_csv ${DBNAME} ${FILENAME_FULL} ${NOTE}
elif [ "${ACTION}" == "db_modification" ]; then
	db_modification ${DBNAME}
elif [ "${ACTION}" == "update_current_bonus_2log" ]; then
	update_current_bonus_2log ${DBNAME}
elif [ "${ACTION}" == "update_modified_bonus_2log" ]; then
	update_modified_bonus_2log ${DBNAME}
elif [ "${ACTION}" == "update_online_bonus_2tbuser" ]; then
	update_online_bonus_2tbuser ${DBNAME}
elif [ "${ACTION}" == "update_checked_bonus_2log" ]; then
	update_checked_bonus_2log ${DBNAME}
elif [ "${ACTION}" == "update_date_status_2log" ]; then
	update_date_status_2log ${DBNAME}
elif [ "${ACTION}" == "output" ]; then
	output ${DBNAME}
elif [ "${ACTION}" == "output_stdout" ]; then
	output_stdout ${DBNAME}
elif [ "${ACTION}" == "output_csv" ]; then
	output_csv ${DBNAME}
elif [ "${ACTION}" == "restore" ]; then
	restore ${DBNAME} ${FILENAME_FULL}
elif [ "${ACTION}" == "restore_file" ]; then
	restore_file ${FILENAME_FULL}
elif [ "${ACTION}" == "restore_db" ]; then
	restore_db ${DBNAME}
elif [ "${ACTION}" == "output_stdout_tbuser" ]; then
	output_stdout_tbuser ${DBNAME}
elif [ "${ACTION}" == "output_original_file" ]; then
	output_original_file ${FILENAME_FULL}
elif [ "${ACTION}" == "prepare" ]; then
	prepare ${DBNAME} ${FILENAME_FULL} ${NOTE}
elif [ "${ACTION}" == "execute" ]; then
	execute ${DBNAME} ${FILENAME_FULL} ${NOTE}
elif [ "${ACTION}" == "all" ]; then
	all ${DBNAME} ${FILENAME_FULL} ${NOTE}
fi
