#!/usr/bin/env bash

set -euo pipefail

echo "正在准备部署到阿里云容器镜像服务..."

# 阿里云容器镜像服务参数
# 请根据您的实际情况修改以下参数

# 阿里云容器镜像服务地域
REGISTRY_REGION="cn-hangzhou"

# 命名空间
NAMESPACE="hmm316"

# 镜像仓库名称
REPOSITORY_NAME="contract-approval"

# 镜像版本默认值
IMAGE_VERSION="v1.0.0"

# 阿里云容器镜像服务登录名
USERNAME="742065561@qq.com"

# Registry 登录密码
# 为安全起见，不在脚本中硬编码密码
PASSWORD=""

REGISTRY_HOST="registry.${REGISTRY_REGION}.aliyuncs.com"
IMAGE_NAME="${REGISTRY_HOST}/${NAMESPACE}/${REPOSITORY_NAME}:${IMAGE_VERSION}"

# 手动输入镜像版本
read -r -p "请输入镜像版本(例如: v1.0.0): " INPUT_VERSION
if [ -n "${INPUT_VERSION}" ]; then
    IMAGE_VERSION="${INPUT_VERSION}"
fi

IMAGE_NAME="${REGISTRY_HOST}/${NAMESPACE}/${REPOSITORY_NAME}:${IMAGE_VERSION}"

# 显示将要使用的配置
echo "将使用以下配置:"
echo "地域: ${REGISTRY_REGION}"
echo "命名空间: ${NAMESPACE}"
echo "仓库名称: ${REPOSITORY_NAME}"
echo "镜像版本: ${IMAGE_VERSION}"
echo "登录用户: ${USERNAME}"
echo "完整镜像名: ${IMAGE_NAME}"
echo ""

# 确认是否继续
read -r -p "是否继续部署? (y/n): " CONFIRM
if [ "${CONFIRM}" != "y" ] && [ "${CONFIRM}" != "Y" ]; then
    echo "部署已取消"
    exit 0
fi

if ! command -v docker >/dev/null 2>&1; then
    echo "未检测到 docker 命令，请先安装 Docker。"
    exit 1
fi

if [ -z "${PASSWORD}" ]; then
    read -r -s -p "请输入阿里云镜像仓库密码: " PASSWORD
    echo ""
fi

# 登录阿里云容器镜像服务
echo "正在登录阿里云容器镜像服务..."
printf "%s" "${PASSWORD}" | docker login --username="${USERNAME}" --password-stdin "${REGISTRY_HOST}"

# 构建镜像
echo "正在构建镜像..."
docker build -t "${IMAGE_NAME}" .

# 推送镜像
echo "正在推送镜像到阿里云..."
docker push "${IMAGE_NAME}"

echo "镜像已成功推送到阿里云容器镜像服务!"
echo "镜像地址: ${IMAGE_NAME}"

echo "创建部署配置文件..."
cat > docker-compose-aliyun.yml <<EOL
services:
  app:
    image: ${IMAGE_NAME}
    container_name: contract-approval-app
    restart: always
    environment:
      NODE_ENV: production
      HOSTNAME: 0.0.0.0
      PORT: 3001
      JWT_SECRET: \${JWT_SECRET:-change-me-in-production}
    ports:
      - "\${APP_PORT:-3001}:3001"
    volumes:
      - ./data:/app/data
      - ./public/uploads:/app/public/uploads
EOL

echo "部署配置文件已创建: docker-compose-aliyun.yml"
echo "服务器部署命令:"
echo "docker compose -f docker-compose-aliyun.yml up -d"
