#!/usr/bin/env bash
set -euo pipefail

# 腳本名稱: drop_database_for_current_machine_by_pattern
# 參數說明：
# $1: type (prefix / postfix / contain)
# $2: pattern
# $3: backup_flag (1:備份 / 0:不備份，預設 1)
#
# B 方案行為：
# - 找不到任何符合 pattern 的資料庫：視為正常，exit 0
# - 只有查詢失敗 / 備份失敗 / DROP 失敗 才 exit 非 0

if [ -z "${2-}" ]; then
    echo "Usage: $0 <type: prefix / postfix / contain> <pattern> [backup_flag: 1|0]"
    exit 1
fi

TYPE="${1-}"
PATTERN="${2-}"
BACKUP_FLAG="${3:-1}"   # 預設為 1 (備份)

# 檢查 BACKUP_FLAG 合法性
if [[ "$BACKUP_FLAG" != "0" && "$BACKUP_FLAG" != "1" ]]; then
    echo "Error: backup_flag must be 0 or 1, got '$BACKUP_FLAG'"
    echo "Usage: $0 <type: prefix / postfix / contain> <pattern> [backup_flag: 1|0]"
    exit 1
fi

# 避免 pattern 含單引號導致 SQL 斷裂
PATTERN_SQL="${PATTERN//\'/\'\'}"

sql=""
case "${TYPE}" in
    prefix)
        sql="SELECT datname FROM pg_database WHERE datname ~ '^${PATTERN_SQL}';"
        ;;
    postfix)
        sql="SELECT datname FROM pg_database WHERE datname ~ '${PATTERN_SQL}\$';"
        ;;
    contain)
        sql="SELECT datname FROM pg_database WHERE datname ~ '${PATTERN_SQL}';"
        ;;
    *)
        echo "Unknown type for ${TYPE}!"
        echo "Valid types: prefix / postfix / contain"
        exit 1
        ;;
esac

# 查詢失敗視為真正錯誤（exit 非 0）
DBNAME_LISTS="$(
    psql -U postgres -v ON_ERROR_STOP=1 -Atqc "${sql}"
)"

# 沒有符合者：正常情境（B 方案重點）
if [ -z "${DBNAME_LISTS}" ]; then
    echo "[INFO] No database matched (type=${TYPE}, pattern=${PATTERN}). Nothing to do."
    exit 0
fi

fail=0

while IFS= read -r dbname; do
    [ -z "$dbname" ] && continue

    echo "==> ${dbname}"

    if [[ "$BACKUP_FLAG" -eq 1 ]]; then
        echo "  - Backup ${dbname}"
        if [ ! -x "$HOME/bin/DBbackup" ]; then
            echo "[ERROR] DBbackup not found or not executable: $HOME/bin/DBbackup" >&2
            fail=1
            continue
        fi
        if ! "$HOME/bin/DBbackup" "${dbname}"; then
            echo "[ERROR] Backup failed: ${dbname}" >&2
            fail=1
            continue
        fi
    else
        echo "  - Skip backup for ${dbname}"
    fi

    echo "  - Drop database ${dbname}"
    if ! psql -U postgres -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${dbname}\";"; then
        echo "[ERROR] Drop database failed: ${dbname}" >&2
        fail=1
        continue
    fi
done <<< "${DBNAME_LISTS}"

if [ "$fail" -ne 0 ]; then
    exit 1
fi

exit 0

