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

REMOTE_MACHINE_NAME="$1"
LOCAL_DIRECTORY_NAME="$2"
[ -z "${LOCAL_DIRECTORY_NAME}" ] && DIRECTORY_NAME=$(date +"%Y%m%dT%H%M%S") || DIRECTORY_NAME=$(basename ${LOCAL_DIRECTORY_NAME})

mkdir -p /tmp/itemmall_${DIRECTORY_NAME}; cd /tmp/itemmall_${DIRECTORY_NAME};

num=0
echo "######"
echo "Dump all promotion tables"
echo
TABLES=$(psql -U postgres Tools -tAc "SELECT table_name_db FROM web_table_mapping WHERE table_name_db NOT LIKE 'x_%' ORDER BY table_name_db;")
if [[ -z "$TABLES" ]]; then
    echo "❌ Tools.web_table_mapping 抓不到 table list（條件: NOT LIKE 'x_%'）" >&2
    exit 1
fi
for table in $TABLES; do
    ((num++))
    echo "Dump ${table} [${num}]..."
    pg_dump -U postgres $ACCOUNT_DB_NAME -t ${table} > ${table}.sql
done
echo "######"
echo

echo
[ -z "${REMOTE_MACHINE_NAME}" ] && echo "Rsync to Remote Machine"; cd /tmp; tar cvzf - itemmall_${DIRECTORY_NAME} | ssh ${REMOTE_MACHINE_NAME} '(cd /tmp && tar xvzf -)'
echo

echo "Total Dump Tables: ${num}"
echo
[ -z "${REMOTE_MACHINE_NAME}" ] && echo "ssh -o StrictHostKeyChecking=no ${REMOTE_MACHINE_NAME} \"cd /tmp/itemmall_${DIRECTORY_NAME}; $HOME/bin/restore_all_promotion_tables /tmp/itemmall_${DIRECTORY_NAME}\""; ssh -o StrictHostKeyChecking=no ${REMOTE_MACHINE_NAME} "cd /tmp/itemmall_${DIRECTORY_NAME}; $HOME/bin/restore_all_promotion_tables /tmp/itemmall_${DIRECTORY_NAME}"
