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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
REPO_ROOT="$(cd "$TEST_ROOT/../../.." && pwd)"

PLUGIN_DIR="$REPO_ROOT/src/metric/client-plugins/all-in-one-full"
FTP_CONTAINER="argus-ftp"

if [[ ! -d "$PLUGIN_DIR" ]]; then
  echo "[SYS-METRIC] Metric client plugin directory not found: $PLUGIN_DIR" >&2
  exit 1
fi

if [[ -f "$TEST_ROOT/.env" ]]; then
  # shellcheck source=/dev/null
  source "$TEST_ROOT/.env"
fi

OWNER="${ARGUS_BUILD_UID:-2133}:${ARGUS_BUILD_GID:-2015}"

resolve_output_dir() {
  local host_mount
  if docker ps --format '{{.Names}}' | grep -q "^${FTP_CONTAINER}$"; then
    host_mount=$(docker inspect "$FTP_CONTAINER" --format '{{range .Mounts}}{{if eq .Destination "/private/argus/ftp"}}{{.Source}}{{end}}{{end}}' 2>/dev/null || true)
    if [[ -n "$host_mount" ]]; then
      echo "$host_mount/share"
      return 0
    fi
  fi
  echo "$TEST_ROOT/private/argus/metric/ftp/share"
}

OUTPUT_DIR="$(resolve_output_dir)"
mkdir -p "$OUTPUT_DIR"

if [[ ! -w "$OUTPUT_DIR" ]]; then
  echo "[SYS-METRIC] 无法写入 FTP 输出目录: $OUTPUT_DIR" >&2
  echo "             请确认目录权限与 ARGUS_BUILD_UID/GID 一致" >&2
  exit 1
fi

pushd "$PLUGIN_DIR" >/dev/null

echo "[SYS-METRIC] Bumping metric artifact version..."
bash scripts/version-manager.sh bump minor

VERSION_FILE="config/VERSION"
if [[ ! -f "$VERSION_FILE" ]]; then
  echo "[SYS-METRIC] VERSION 文件缺失: $VERSION_FILE" >&2
  exit 1
fi

VERSION=$(tr -d '\n' < "$VERSION_FILE")
echo "[SYS-METRIC] 当前版本: $VERSION"

echo "[SYS-METRIC] Packaging metric artifact..."
bash scripts/package_artifact.sh --force

echo "[SYS-METRIC] Publishing artifact to FTP share..."
bash scripts/publish_artifact.sh "$VERSION" --output-dir "$OUTPUT_DIR" --owner "$OWNER"

popd >/dev/null

echo "[SYS-METRIC] Metric artifact published to $OUTPUT_DIR"
