#!/bin/bash

# 泉友米车友会 - Docker 构建脚本

set -e

# ==========================================
# 版本号配置（修改这里即可）
# ==========================================
VERSION_FILE=".version"
MAJOR=0
MINOR=0

# 读取或初始化补丁版本号
if [ -f "$VERSION_FILE" ]; then
    PATCH=$(cat "$VERSION_FILE")
else
    PATCH=1
fi

# 组合完整版本号
VERSION="$MAJOR.$MINOR.$PATCH"

echo "=========================================="
echo "泉友米车友会 Docker 镜像构建"
echo "版本: $VERSION"
echo "=========================================="

# 检查 Docker 是否安装
if ! command -v docker &> /dev/null; then
    echo "错误: Docker 未安装，请先安装 Docker"
    exit 1
fi

# 构建镜像
echo ""
echo "开始构建 Docker 镜像..."
docker build -t quanyoumi-app:$VERSION -t quanyoumi-app:latest .

# 构建成功后自动递增版本号
NEXT_PATCH=$((PATCH + 1))
echo $NEXT_PATCH > "$VERSION_FILE"

echo ""
echo "=========================================="
echo "构建完成！版本号已更新"
echo "=========================================="
echo ""
echo "当前版本: $VERSION"
echo "下次版本: $MAJOR.$MINOR.$NEXT_PATCH"
echo ""
echo "镜像信息:"
docker images | grep quanyoumi-app
echo ""

# 标记镜像到阿里云仓库
echo "正在标记镜像到阿里云仓库..."
docker tag quanyoumi-app:$VERSION registry.cn-hangzhou.aliyuncs.com/yvan329/quanyoumi-app:$VERSION
docker tag quanyoumi-app:latest registry.cn-hangzhou.aliyuncs.com/yvan329/quanyoumi-app:latest

echo ""
echo "正在推送镜像到阿里云仓库..."
docker push registry.cn-hangzhou.aliyuncs.com/yvan329/quanyoumi-app:$VERSION
docker push registry.cn-hangzhou.aliyuncs.com/yvan329/quanyoumi-app:latest

echo ""
echo "=========================================="
echo "推送完成！"
echo "=========================================="
echo ""
echo "当前版本: $VERSION"
echo "下次版本: $MAJOR.$MINOR.$NEXT_PATCH"
echo ""
echo "镜像地址:"
echo "  registry.cn-hangzhou.aliyuncs.com/yvan329/quanyoumi-app:$VERSION"
echo "  registry.cn-hangzhou.aliyuncs.com/yvan329/quanyoumi-app:latest"
echo ""
echo "在 NAS 上使用:"
echo "  docker pull registry.cn-hangzhou.aliyuncs.com/yvan329/quanyoumi-app:$VERSION"
echo "  docker-compose up -d"
echo ""
echo "提示: 如需修改主版本号或次版本号，请编辑 build.sh 文件顶部的 MAJOR 和 MINOR 变量"
echo ""
