#!/usr/bin/env bash
#
# 将仓库最新源码同步到 deployment/ 发布目录（开发机/CI 执行）
# 用法: bash deployment/sync_release.sh
#
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DEPLOY_DIR="${ROOT_DIR}/deployment"

echo "[sync] 根目录: ${ROOT_DIR}"
echo "[sync] 发布目录: ${DEPLOY_DIR}"

copy_tree() {
  local src="$1"
  local dst="$2"
  if [[ ! -d "${src}" ]]; then
    echo "[sync] 跳过（不存在）: ${src}"
    return 0
  fi
  rm -rf "${dst}"
  cp -a "${src}" "${dst}"
  echo "[sync] ${src} -> ${dst}"
}

copy_file() {
  local src="$1"
  local dst="$2"
  if [[ ! -f "${src}" ]]; then
    echo "[sync] 跳过（不存在）: ${src}"
    return 0
  fi
  cp -f "${src}" "${dst}"
  echo "[sync] ${src} -> ${dst}"
}

copy_tree "${ROOT_DIR}/app" "${DEPLOY_DIR}/app"
copy_tree "${ROOT_DIR}/database" "${DEPLOY_DIR}/database"
copy_tree "${ROOT_DIR}/migrations" "${DEPLOY_DIR}/migrations"

for file in requirements.txt gunicorn_config.py __init__.py; do
  copy_file "${ROOT_DIR}/${file}" "${DEPLOY_DIR}/${file}"
done
copy_file "${ROOT_DIR}/alembic.ini" "${DEPLOY_DIR}/alembic.ini"

if [[ ! -f "${DEPLOY_DIR}/wsgi.py" ]]; then
  cat >"${DEPLOY_DIR}/wsgi.py" <<'EOF'
"""WSGI entry point for production deployment."""

from app import create_app

application = create_app()
app = application
EOF
  echo "[sync] 已生成 ${DEPLOY_DIR}/wsgi.py"
fi

mkdir -p "${DEPLOY_DIR}/scripts"
for script in dataops-common.sh deploy_dataops.sh run_dataops.sh start_dataops.sh stop_dataops.sh restart_dataops.sh; do
  copy_file "${ROOT_DIR}/scripts/${script}" "${DEPLOY_DIR}/scripts/${script}"
done

# 统一 LF，避免 Windows 编辑导致 bash 报错
if command -v sed >/dev/null 2>&1; then
  find "${DEPLOY_DIR}" -type f \( -name '*.sh' -o -name 'dataops.env' -o -name '.env.production.example' \) \
    -exec sed -i 's/\r$//' {} + 2>/dev/null || true
fi

chmod +x "${DEPLOY_DIR}/deploy_dataops.sh" "${DEPLOY_DIR}/sync_release.sh" 2>/dev/null || true
chmod +x "${DEPLOY_DIR}/scripts/"*.sh 2>/dev/null || true

echo "[sync] 完成。下一步: cd deployment && bash package_release.sh"
