#!/bin/bash
# 推送 Docker 镜像到私有仓库脚本

set -euo pipefail

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 私有仓库配置 (来自 README.md)
REGISTRY_URL="docker-registry.julyhaven.com"
REGISTRY_USER="hucs"
REGISTRY_PASS="hucsdev"
PROJECT_PATH="peipei/backend"

echo -e "${GREEN}=== 推送 PeiPei 后端镜像到私有仓库 ===${NC}"

# 获取 UTC+8 时间戳
TIMESTAMP=$(TZ='Asia/Shanghai' date +"%Y-%m-%d-%Hh-%Mm")
echo -e "${YELLOW}推送时间戳 (UTC+8): ${TIMESTAMP}${NC}"

# 本地镜像名称 (始终推送 amd64 版本到服务器)
LOCAL_IMAGE="peipei-backend"
LOCAL_TAG="latest-amd64"  # 服务器使用 amd64 架构

# 远程镜像名称和标签
REMOTE_IMAGE="${REGISTRY_URL}/${PROJECT_PATH}"
VERSION_TAG="${TIMESTAMP}"
LATEST_TAG="latest"

echo -e "${BLUE}私有仓库地址: ${REGISTRY_URL}${NC}"
echo -e "${BLUE}项目路径: ${PROJECT_PATH}${NC}"
echo -e "${BLUE}远程镜像: ${REMOTE_IMAGE}${NC}"

# 检查本地镜像是否存在
if ! docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "^${LOCAL_IMAGE}:${LOCAL_TAG}$"; then
    echo -e "${RED}错误: 本地镜像 ${LOCAL_IMAGE}:${LOCAL_TAG} 不存在${NC}"
    echo -e "${YELLOW}请先运行: ./build-docker.sh amd64${NC}"
    echo -e "${YELLOW}当前可用的镜像:${NC}"
    docker images --format "table {{.Repository}}\t{{.Tag}}" | grep "^${LOCAL_IMAGE}\s"
    exit 1
fi

# 登录私有仓库
echo -e "${GREEN}登录私有 Docker 仓库...${NC}"
echo "${REGISTRY_PASS}" | docker login "${REGISTRY_URL}" -u "${REGISTRY_USER}" --password-stdin

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 登录私有仓库失败!${NC}"
    exit 1
fi

echo -e "${GREEN}✅ 登录成功!${NC}"

# 标记镜像 - 版本标签
echo -e "${GREEN}标记镜像: ${LOCAL_IMAGE}:${LOCAL_TAG} -> ${REMOTE_IMAGE}:${VERSION_TAG}${NC}"
docker tag "${LOCAL_IMAGE}:${LOCAL_TAG}" "${REMOTE_IMAGE}:${VERSION_TAG}"

# 标记镜像 - latest 标签
echo -e "${GREEN}标记镜像: ${LOCAL_IMAGE}:${LOCAL_TAG} -> ${REMOTE_IMAGE}:${LATEST_TAG}${NC}"
docker tag "${LOCAL_IMAGE}:${LOCAL_TAG}" "${REMOTE_IMAGE}:${LATEST_TAG}"

# 推送版本标签
echo -e "${GREEN}推送版本标签镜像...${NC}"
docker push "${REMOTE_IMAGE}:${VERSION_TAG}"

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 推送版本标签失败!${NC}"
    exit 1
fi

# 推送 latest 标签
echo -e "${GREEN}推送 latest 标签镜像...${NC}"
docker push "${REMOTE_IMAGE}:${LATEST_TAG}"

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 推送 latest 标签失败!${NC}"
    exit 1
fi

echo -e "${GREEN}✅ 所有镜像推送成功!${NC}"

# 显示推送结果
echo -e "\n${BLUE}推送的镜像:${NC}"
echo -e "  📦 ${REMOTE_IMAGE}:${VERSION_TAG}"
echo -e "  📦 ${REMOTE_IMAGE}:${LATEST_TAG}"

echo -e "\n${YELLOW}服务器部署命令:${NC}"
echo -e "  docker pull ${REMOTE_IMAGE}:${VERSION_TAG}"
echo -e "  docker pull ${REMOTE_IMAGE}:${LATEST_TAG}"

echo -e "\n${YELLOW}更新 docker-compose.yml 中的镜像:${NC}"
echo -e "  image: ${REMOTE_IMAGE}:${VERSION_TAG}"

echo -e "\n${BLUE}注意: 此脚本推送 amd64 架构镜像到服务器${NC}"

# 清理本地标记的远程镜像标签 (可选)
echo -e "\n${GREEN}清理本地远程标签...${NC}"
docker rmi "${REMOTE_IMAGE}:${VERSION_TAG}" "${REMOTE_IMAGE}:${LATEST_TAG}" 2>/dev/null || true

echo -e "\n${GREEN}🚀 推送完成!${NC}"