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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

load_env_file() {
  local file="$1"
  [[ -f "$file" ]] || return 0

  while IFS= read -r line || [[ -n "$line" ]]; do
    line="${line#${line%%[![:space:]]*}}"
    line="${line%${line##*[![:space:]]}}"
    [[ -z "$line" ]] && continue
    [[ "$line" == \#* ]] && continue
    [[ "$line" != *=* ]] && continue

    local key="${line%%=*}"
    local val="${line#*=}"
    key="${key#${key%%[![:space:]]*}}"
    key="${key%${key##*[![:space:]]}}"
    [[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue

    if [[ "$val" =~ ^\".*\"$ ]]; then
      val="${val:1:${#val}-2}"
    elif [[ "$val" =~ ^\'.*\'$ ]]; then
      val="${val:1:${#val}-2}"
    fi

    if [[ -z "${!key:-}" ]]; then
      export "$key=$val"
    fi
  done < "$file"
}

usage() {
  cat <<'EOF' >&2
Usage:
  bash build-push-acr.sh <acr_password>
  # or:
  ACR_PASSWORD=... ACR_USERNAME=... REPO_URL=... NAMESPACE=... REPO_NAME=... IMAGE_TAG=... bash build-push-acr.sh

Required:
  acr_password (positional arg #1) OR env ACR_PASSWORD

Optional:
  ENV_FILE       env file to load (default: ../deploy/.env if exists)
  ACR_USERNAME   default: aipper@qq.com
  REPO_URL       registry host (ACR). Default: registry.cn-hangzhou.aliyuncs.com
  NAMESPACE      ACR namespace. Default: aipper
  REPO_NAME      repository name. Default: digital-archive-frontend
  IMAGE_TAG      default: YYYYMMDDHHMM
  PKG_MANAGER    pnpm|npm (build-arg)
  NPM_REGISTRY   custom npm registry (build-arg)
  DRY_RUN=1      print computed image ref and exit

Compatibility:
  REPO_URL -> ACR_REGISTRY
  NAMESPACE -> ACR_NAMESPACE
EOF
}

if [[ -n "${ENV_FILE:-}" ]]; then
  load_env_file "$ENV_FILE"
else
  load_env_file "$script_dir/../deploy/.env"
fi

if [[ -z "${ACR_PASSWORD:-}" && -n "${1:-}" ]]; then
  export ACR_PASSWORD="$1"
fi
if [[ -z "${ACR_USERNAME:-}" && -n "${2:-}" ]]; then
  export ACR_USERNAME="$2"
fi

if [[ -z "${ACR_REGISTRY:-}" && -n "${REPO_URL:-}" ]]; then
  export ACR_REGISTRY="$REPO_URL"
fi
if [[ -z "${ACR_NAMESPACE:-}" && -n "${NAMESPACE:-}" ]]; then
  export ACR_NAMESPACE="$NAMESPACE"
fi

export REPO_URL="${REPO_URL:-${ACR_REGISTRY:-registry.cn-hangzhou.aliyuncs.com}}"
export NAMESPACE="${NAMESPACE:-${ACR_NAMESPACE:-aipper}}"
export REPO_NAME="${REPO_NAME:-${IMAGE_REPO:-digital-archive-frontend}}"
export IMAGE_TAG="${IMAGE_TAG:-$(date +"%Y%m%d%H%M")}" 

export ACR_REGISTRY="${ACR_REGISTRY:-$REPO_URL}"
export ACR_NAMESPACE="${ACR_NAMESPACE:-$NAMESPACE}"
export IMAGE_REPO="${IMAGE_REPO:-$REPO_NAME}"
export ACR_USERNAME="${ACR_USERNAME:-aipper@qq.com}"

if [[ -z "${ACR_PASSWORD:-}" ]]; then
  echo "错误：请在运行脚本时传递密码，例如：bash build-push-acr.sh your-acr-password" >&2
  usage
  exit 1
fi

image_repo="$IMAGE_REPO"
image_tag="$IMAGE_TAG"

image_ref="${ACR_REGISTRY}/${ACR_NAMESPACE}/${image_repo}:${image_tag}"

if [[ "${DRY_RUN:-}" == "1" ]]; then
  echo "DRY_RUN=1"
  echo "IMAGE_REF=$image_ref"
  exit 0
fi

printf '%s' "$ACR_PASSWORD" | docker login "$ACR_REGISTRY" -u "$ACR_USERNAME" --password-stdin

build_args=()
if [[ -n "${PKG_MANAGER:-}" ]]; then
  build_args+=(--build-arg "PKG_MANAGER=${PKG_MANAGER}")
fi
if [[ -n "${NPM_REGISTRY:-}" ]]; then
  build_args+=(--build-arg "NPM_REGISTRY=${NPM_REGISTRY}")
fi

if docker buildx version >/dev/null 2>&1; then
  docker buildx build \
    -f "$script_dir/Dockerfile" \
    -t "$image_ref" \
    --load \
    "${build_args[@]}" \
    "$script_dir"
else
  docker build \
    -f "$script_dir/Dockerfile" \
    -t "$image_ref" \
    "${build_args[@]}" \
    "$script_dir"
fi

docker push "$image_ref"

echo "Pushed: $image_ref"
echo "WEB_IMAGE=$image_ref"
