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

usage() {
    exec echo "Usage: $0 <DB_TYPE: ACCOUNTDB / GAMEDB / WORLDDB / SOCIETYDB>"
}

# 參數檢查
[[ $# -lt 1 ]] && usage
DB_TYPE="$1"

if [ "$HOST_NAME" == "TEST" -o "$HOST_NAME" == "SUB" -o "$HOST_NAME" == "SUBMIT" -o "$HOST_NAME" == "DATA" -o "$HOST_NAME" == "DLC" -o "$HOST_NAME" == "TIME1" -o "$HOST_NAME" == "MEDIA" ] || [[ "$HOST_NAME" == *"MERGE"* ]] ; then
    DIRECTORY_NAME="$HOME/common-TEST/db"
else
    DIRECTORY_NAME="$HOME/common/db"
fi

# === 取得維護日 ===
[ -z "${MaintenanceDate}" ] && maintenance="3" || maintenance=${MaintenanceDate}

# === 取得今天資訊 ===
today_weekday=$(date +%u)     # 1–7 (1=Monday)
today_month=$(date +%m)
today_day=$(date +%d)

# === 判斷是否為本月第一個指定星期 ===
# 找出本月第一天的星期幾
first_day_weekday=$(date -d "$(date +%Y-%m-01)" +%u)

# 計算本月第一個指定 weekday 的日期（例如第一個週三是幾號）
if (( maintenance >= first_day_weekday )); then
    first_maintenance_day=$(( 1 + (maintenance - first_day_weekday) ))
else
    first_maintenance_day=$(( 1 + (7 - (first_day_weekday - maintenance)) ))
fi

# === 判斷是否為第一個週 X ===
if [[ "$today_weekday" -eq "$maintenance" && "$today_day" -eq "$first_maintenance_day" ]]; then
    echo "[INFO] It's the first Weekday $maintenance of the month → Running VACUUM FULL"
    DO_VACUUM_FULL="1"
else
    echo "[INFO] Regular day → Running VACUUM ANALYZE"
    DO_VACUUM_FULL="0"
fi

echo "=== Info ==="
echo "Maintenance: ${maintenance}, DO_VACUUM_FULL: ${DO_VACUUM_FULL}"
echo

case "${DB_TYPE}" in
    ACCOUNTDB)
        cd $DIRECTORY_NAME; cp -arf db_account_alter db_account_alter_byV
        sed -i '/print "\\n";/ s/^/#/' db_account_alter_byV
        sed -i -e '/print "backup db GDA_\$BAKDATE\\n"/ s/^/#/' db_account_alter_byV
        sed -i -e 's/system (\"pg_dump/#system (\"pg_dump/g;s/^\(.*vacuum.*\)$/#\1/g' db_account_alter_byV
        sed -i -e '/system (\$BAKDATE=`date +%y%m%d%H%M.gz`);/ s/^/#/' db_account_alter_byV
        sed -i -e '/print "\\x1b\[0m\\n";/ s/^/#/' db_account_alter_byV

        for ACCOUNTDB in $(find $HOME/servers1 -maxdepth 1 -type f -name "setup.ini" -exec grep "^AccountDBName=" {} + | cut -d= -f2); do
            cd $DIRECTORY_NAME; echo ${ACCOUNTDB} | colorize yellow black; $(which perl) db_account_alter_byV :${ACCOUNTDB} &
            if [ "${DO_VACUUM_FULL}" == "1" ]; then
                psql -U postgres ${ACCOUNTDB} -c "VACUUM FULL;"
            else
                psql -U postgres ${ACCOUNTDB} -c "VACUUM ANALYZE;"
            fi
        done
        ;;
    GAMEDB|gamedb)
        cd $DIRECTORY_NAME; cp -arf db_game_alter db_game_alter_byV
        sed -i '/print "\\n";/ s/^/#/' db_game_alter_byV
        sed -i -e '/print "backup db GameDB_\$BAKDATE\\n"/ s/^/#/' db_game_alter_byV
        sed -i -e 's/system (\"pg_dump/#system (\"pg_dump/g;s/^\(.*vacuum.*\)$/#\1/g' db_game_alter_byV
        sed -i -e '/system (\$BAKDATE=`date +%y%m%d%H%M.gz`);/ s/^/#/' db_game_alter_byV
        sed -i -e '/print "\\x1b\[0m\\n";/ s/^/#/' db_game_alter_byV

        for GAMEDB in $(find $HOME/servers* -maxdepth 1 -type f -name "setup.ini" -exec grep "^GameDB=" {} + | cut -d= -f2); do
            cd $DIRECTORY_NAME; echo ${GAMEDB} | colorize yellow black; $(which perl) db_game_alter_byV :${GAMEDB} &
            if [ "${DO_VACUUM_FULL}" == "1" ]; then
                psql -U postgres ${GAMEDB} -c "VACUUM FULL;"
            else
                psql -U postgres ${GAMEDB} -c "VACUUM ANALYZE;"
            fi
        done
        ;;
    WORLDDB|worlddb)
        cd $DIRECTORY_NAME; cp -arf db_world_alter db_world_alter_byV
        sed -i '/print "\\n";/ s/^/#/' db_world_alter_byV
        sed -i -e '/print "backup db WorldDB_\$BAKDATE\\n"/ s/^/#/' db_world_alter_byV
        sed -i -e 's/system (\"pg_dump/#system (\"pg_dump/g;s/^\(.*vacuum.*\)$/#\1/g' db_world_alter_byV
        sed -i -e '/system (\$BAKDATE=`date +%y%m%d%H%M.gz`);/ s/^/#/' db_world_alter_byV
        sed -i -e '/print "\\x1b\[0m\\n";/ s/^/#/' db_world_alter_byV

        for WORLDDB in $(find $HOME/servers*/WorldServer* -maxdepth 1 -type f -name "setup.ini" -exec grep "^WorldDBName=" {} + | cut -d= -f2); do
            cd $DIRECTORY_NAME; echo ${WORLDDB} | colorize yellow black; $(which perl) db_world_alter_byV :${WORLDDB} &
            if [ "${DO_VACUUM_FULL}" == "1" ]; then
                psql -U postgres ${WORLDDB} -c "VACUUM FULL;"
            else
                psql -U postgres ${WORLDDB} -c "VACUUM ANALYZE;"
            fi
        done
        ;;
    SOCIETYDB|societydb)
        cd $DIRECTORY_NAME; cp -arf db_society_alter db_society_alter_byV
        sed -i '/print "\\n";/ s/^/#/' db_society_alter_byV
        sed -i -e '/print "backup db SocietyDB_\$BAKDATE\\n"/ s/^/#/' db_society_alter_byV
        sed -i -e 's/system (\"pg_dump/#system (\"pg_dump/g;s/^\(.*vacuum.*\)$/#\1/g' db_society_alter_byV
        sed -i -e '/system (\$BAKDATE=`date +%y%m%d%H%M.gz`);/ s/^/#/' db_society_alter_byV
        sed -i -e '/print "\\x1b\[0m\\n";/ s/^/#/' db_society_alter_byV

        for SOCIETYDB in $(find $HOME/servers*/SocietyServer* -maxdepth 1 -type f -name "setup.ini" -exec grep "^SocietyDBName=" {} + | cut -d= -f2); do
            cd $DIRECTORY_NAME; echo ${SOCIETYDB} | colorize yellow black; $(which perl) db_society_alter_byV :${SOCIETYDB} &
            if [ "${DO_VACUUM_FULL}" == "1" ]; then
                psql -U postgres ${SOCIETYDB} -c "VACUUM FULL;"
            else
                psql -U postgres ${SOCIETYDB} -c "VACUUM ANALYZE;"
            fi
        done
        ;;
    *)
        echo "ERROR: Unknown DB_TYPE for ${DB_TYPE}"; usage
        ;;
esac
