#!/usr/bin/env bash
# PostgreSQL 备份恢复脚本
# 用法: BACKUP_PASSPHRASE=xxx ./docker/restore.sh /backups/erp_20260521_020000.sql.gz.enc
set -euo pipefail

BACKUP_FILE="${1:?用法: restore.sh <备份文件路径>}"
PG_HOST="${PGHOST:-postgres}"
PG_PORT="${PGPORT:-5432}"
PG_USER="${PGUSER:-erp}"
PG_DB="${PGDATABASE:-erp}"

if [ ! -f "${BACKUP_FILE}" ]; then
    echo "错误: 文件不存在: ${BACKUP_FILE}" >&2
    exit 1
fi

echo "[$(date -Iseconds)] 恢复目标: ${PG_HOST}:${PG_PORT}/${PG_DB}"
echo "[$(date -Iseconds)] 备份文件: ${BACKUP_FILE}"

# 解密（如果是加密文件）
if [[ "${BACKUP_FILE}" == *.enc ]]; then
    if [ -z "${BACKUP_PASSPHRASE:-}" ]; then
        echo "错误: 加密备份需要设置 BACKUP_PASSPHRASE 环境变量" >&2
        exit 1
    fi
    DECRYPTED="${BACKUP_FILE%.enc}"
    echo "[$(date -Iseconds)] 解密中..."
    openssl enc -d -aes-256-cbc -pbkdf2 -pass "pass:${BACKUP_PASSPHRASE}" \
        -in "${BACKUP_FILE}" -out "${DECRYPTED}"
    BACKUP_FILE="${DECRYPTED}"
fi

# 解压并恢复
echo "[$(date -Iseconds)] 恢复中..."
gunzip -c "${BACKUP_FILE}" | psql -h "${PG_HOST}" -p "${PG_PORT}" -U "${PG_USER}" -d "${PG_DB}"

echo "[$(date -Iseconds)] 恢复完成"

# 清理解密文件
if [ -n "${DECRYPTED:-}" ] && [ -f "${DECRYPTED}" ]; then
    rm -f "${DECRYPTED}"
    echo "[$(date -Iseconds)] 已清理解密临时文件"
fi
