#!/bin/bash

# 脚本名称: pg_import_tables.sh
# 功能: 从URL下载PostgreSQL表备份文件并导入到指定环境
# 用法: ./pg_import_tables.sh <env> <backup_url>

# 检查参数数量
if [ $# -lt 2 ]; then
  echo "错误: 参数不足"
  echo "用法: $0 <环境> <备份文件URL>"
  exit 1
fi

# 获取参数
ENV=$1
BACKUP_URL=$2

# 设置数据库连接参数
case $ENV in
  "int")
    DB_HOST="127.0.0.1"
    DB_PORT="5432"
    DB_USER="farmer"
    DB_PASS="q1w2e3.."
    DB_NAME="msp_int"
    ;;
  "stg")
    DB_HOST="127.0.0.1"
    DB_PORT="5432"
    DB_USER="farmer"
    DB_PASS="q1w2e3.."
    DB_NAME="msp_stg"
    ;;
  "prod")
    DB_HOST="127.0.0.1"
    DB_PORT="5432"
    DB_USER="farmer"
    DB_PASS="q1w2e3.."
    DB_NAME="msp_prod"
    ;;
  *)
    echo "错误: 未知环境 '$ENV'"
    echo "可用环境: int, stg, prod"
    exit 1
    ;;
esac

# 创建临时目录
TMP_DIR="/opt/app/temp/$(uuidgen)"
mkdir -p $TMP_DIR
BACKUP_FILE="$TMP_DIR/backup.tar.gz"

# 下载备份文件
echo "正在下载备份文件..."
if [[ $BACKUP_URL == http* ]]; then
  # 使用curl下载
  curl -s -L -o $BACKUP_FILE "$BACKUP_URL"
  if [ $? -ne 0 ]; then
    echo "错误: 下载备份文件失败"
    rm -rf $TMP_DIR
    exit 1
  fi
else
  # 使用mc下载
  /usr/bin/mc cp "$BACKUP_URL" $BACKUP_FILE
  if [ $? -ne 0 ]; then
    echo "错误: 下载备份文件失败"
    rm -rf $TMP_DIR
    exit 1
  fi
fi

# 解压备份文件
echo "正在解压备份文件..."
tar -xzf $BACKUP_FILE -C $TMP_DIR
if [ $? -ne 0 ]; then
  echo "错误: 解压备份文件失败"
  rm -rf $TMP_DIR
  exit 1
fi

# 导入每个CSV文件
for CSV_FILE in $TMP_DIR/*.csv; do
  if [ -f "$CSV_FILE" ]; then
    TABLE_NAME=$(basename "$CSV_FILE" .csv)
    echo "正在导入表: $TABLE_NAME"
    
    # 使用PGPASSWORD环境变量传递密码
    PGPASSWORD=$DB_PASS /usr/local/bin/psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME \
      -c "\COPY $TABLE_NAME FROM '$CSV_FILE' WITH CSV HEADER"
    
    if [ $? -ne 0 ]; then
      echo "错误: 导入表 $TABLE_NAME 失败"
      rm -rf $TMP_DIR
      exit 1
    fi
    
    echo "表 $TABLE_NAME 导入成功"
  fi
done

# 清理临时目录
rm -rf $TMP_DIR

echo "所有表导入完成！"
exit 0
