#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat >&2 <<'USAGE'
Usage: $0 [--intranet] [--offline] [--tag <image_tag>] [--no-cache]

Options:
  --intranet           使用指定的 PyPI 镜像源（默认清华镜像）。
  --offline            完全离线构建，依赖 offline_wheels/ 目录中的离线依赖包。
  --tag <image_tag>    自定义镜像标签，默认 argus-master:latest。
  --no-cache           不使用 Docker 构建缓存。
USAGE
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
MODULE_ROOT="$PROJECT_ROOT/src/master"
IMAGE_TAG="${IMAGE_TAG:-argus-master:latest}"
DOCKERFILE="src/master/Dockerfile"
BUILD_ARGS=()
OFFLINE_MODE=0
NO_CACHE=0

source "$PROJECT_ROOT/scripts/common/build_user.sh"
load_build_user
BUILD_ARGS+=("--build-arg" "ARGUS_BUILD_UID=${ARGUS_BUILD_UID}" "--build-arg" "ARGUS_BUILD_GID=${ARGUS_BUILD_GID}")

cd "$PROJECT_ROOT"

while [[ "$#" -gt 0 ]]; do
  case "$1" in
    --intranet)
      INTRANET_INDEX="${INTRANET_INDEX:-https://pypi.tuna.tsinghua.edu.cn/simple}"
      BUILD_ARGS+=("--build-arg" "PIP_INDEX_URL=${INTRANET_INDEX}")
      BUILD_ARGS+=("--build-arg" "USE_INTRANET=true")
      shift
      ;;
    --offline)
      OFFLINE_MODE=1
      BUILD_ARGS+=("--build-arg" "USE_OFFLINE=1")
      BUILD_ARGS+=("--build-arg" "USE_INTRANET=true")
      shift
      ;;
    --tag)
      [[ $# -ge 2 ]] || { usage; exit 1; }
      IMAGE_TAG="$2"
      shift 2
      ;;
    --no-cache)
      NO_CACHE=1
      BUILD_ARGS+=("--no-cache")
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage
      exit 1
      ;;
  esac
 done

if [[ "$OFFLINE_MODE" -eq 1 ]]; then
  WHEELS_DIR="$MODULE_ROOT/offline_wheels"
  if [[ ! -d "$WHEELS_DIR" ]]; then
    echo "[ERROR] offline_wheels 目录不存在: $WHEELS_DIR" >&2
    exit 1
  fi
  if ! find "$WHEELS_DIR" -maxdepth 1 -type f -name '*.whl' -print -quit >/dev/null; then
    echo "[ERROR] offline_wheels 目录为空，请先在有网环境执行 scripts/prepare_offline_wheels.sh" >&2
    exit 1
  fi
fi



echo "[INFO] Building image $IMAGE_TAG"
docker build -f "$DOCKERFILE" "${BUILD_ARGS[@]}" -t "$IMAGE_TAG" "$PROJECT_ROOT"
echo "[OK] Image $IMAGE_TAG built"
