#!/bin/bash
set -e

# ============================================
# 本地交叉编译 → 打包镜像 → 通过 SSH 直传 dev 服务器
# 不依赖 Harbor，绕过 HTTPS 问题
# 用法: ./deploy/build.sh [服务名]
#   ./deploy/build.sh           # 全部
#   ./deploy/build.sh gateway   # 单个
# ============================================

DEV_HOST="192.168.100.128"
DEV_USER="root"
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'
YELLOW='\033[1;33m'
NC='\033[0m'

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

# 本地交叉编译（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 "编译完成 ✅"
}

# 打包镜像并通过 SSH 直传 dev 服务器
docker_deploy() {
  local name=$1
  local image="${PROJECT}/${name}:${TAG}"

  log "打包镜像: ${image}"
  DOCKER_BUILDKIT=0 docker build \
    --build-arg SERVICE_NAME="${name}" \
    -t "${image}" \
    -f "${DOCKERFILE}" \
    "${ROOT_DIR}"

  log "传输镜像到 ${DEV_HOST}（通过 SSH 管道，无需 Harbor）..."
  docker save "${image}" | ssh ${DEV_USER}@${DEV_HOST} "docker load"
  log "${name} 部署完成 ✅"
}

# 编译 + 部署单个服务
build_service() {
  local name=$1
  local path=$2
  log "════════════════════════════════════"
  log "服务: ${name}"
  compile_service "$name" "$path"
  docker_deploy "$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}"

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

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

  echo ""
  log "════════════════════════════════════"
  log "全部完成 🎉  镜像已传至 ${DEV_HOST}"
  log "在 dev 服务器上执行: cd /opt/sundynix && docker-compose up -d"
  log "════════════════════════════════════"
}

main "$@"
