#!/bin/bash
set -e

# ============================================
# 本地交叉编译 + 推送 Harbor
# 用法: ./deploy/build.sh [服务名]
#   ./deploy/build.sh           # 构建全部
#   ./deploy/build.sh gateway   # 只构建 gateway
# ============================================

HARBOR="192.168.100.140"
PROJECT="sundynix"
TAG="${BUILD_TAG:-latest}"

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
DOCKERFILE="${ROOT_DIR}/deploy/Dockerfile"
BIN_DIR="${ROOT_DIR}/bin"

GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

log() { echo -e "${GREEN}[BUILD]${NC} $1"; }
err() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# 登录 Harbor
login_harbor() {
  log "登录 Harbor: ${HARBOR}"
  echo "sundynix" | docker login "${HARBOR}" -u admin --password-stdin 2>/dev/null \
    || err "Harbor 登录失败，请检查网络连接"
  log "Harbor 登录成功 ✅"
}

# 本地交叉编译（linux/amd64）
compile_service() {
  local name=$1
  local path=$2

  log "编译: ${name} (linux/amd64)"
  mkdir -p "${BIN_DIR}"
  CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -ldflags="-s -w" \
    -o "${BIN_DIR}/${name}" \
    "${ROOT_DIR}/${path}"
  log "编译完成: bin/${name}"
}

# 打包镜像并推送
docker_push() {
  local name=$1
  local image="${HARBOR}/${PROJECT}/${name}:${TAG}"

  log "打包镜像: ${image}"
  docker build \
    --platform linux/amd64 \
    --build-arg SERVICE_NAME="${name}" \
    -t "${image}" \
    -f "${DOCKERFILE}" \
    "${ROOT_DIR}"

  log "推送: ${image}"
  docker push "${image}"
  log "${name} 推送完成 ✅"
}

# 编译 + 推送单个服务
build_service() {
  local name=$1
  local path=$2

  log "────────────────────────────────────"
  log "服务: ${name}"
  compile_service "$name" "$path"
  docker_push "$name"
}

build_all() {
  build_service "system-rpc" "app/system/rpc"
  build_service "auth-api"   "app/auth/api"
  build_service "system-api" "app/system/api"
  build_service "gateway"    "app/gateway"
}

build_one() {
  case "$1" in
    system-rpc) build_service "system-rpc" "app/system/rpc" ;;
    auth-api)   build_service "auth-api"   "app/auth/api"   ;;
    system-api) build_service "system-api" "app/system/api" ;;
    gateway)    build_service "gateway"    "app/gateway"    ;;
    *)          err "未知服务: $1\n可选: system-rpc | auth-api | system-api | gateway" ;;
  esac
}

main() {
  cd "${ROOT_DIR}"
  login_harbor

  if [ -n "$1" ]; then
    build_one "$1"
  else
    build_all
  fi

  # 清理编译产物
  rm -rf "${BIN_DIR}"

  echo ""
  log "============================================"
  log "构建推送完成 🎉"
  log "镜像地址: ${HARBOR}/${PROJECT}/<服务名>:${TAG}"
  log "============================================"
}

main "$@"
