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

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

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

CONTAINER="argus-metric-test-node"

if ! docker ps --format '{{.Names}}' | grep -q "^${CONTAINER}$"; then
  echo "[SYS-METRIC] 容器 ${CONTAINER} 未运行，无法执行安装" >&2
  exit 1
fi

FTP_HOST="${FTP_SERVER:-172.29.0.40}"
FTP_USER="${FTP_USER:-ftpuser}"
FTP_PASSWORD="${FTP_PASSWORD:-ZGClab1234!}"
FTP_PORT="${FTP_PORT:-21}"

echo "[SYS-METRIC] 在 ${CONTAINER} 内执行安装 (FTP: ${FTP_HOST}:${FTP_PORT})"

docker exec \
  -e FTP_HOST="$FTP_HOST" \
  -e FTP_USER="$FTP_USER" \
  -e FTP_PASSWORD="$FTP_PASSWORD" \
  -e FTP_PORT="$FTP_PORT" \
  "$CONTAINER" bash -c '
set -e

if ! command -v curl &>/dev/null; then
  echo "[SYS-METRIC] curl 未安装，开始安装依赖..."
  apt-get update >/dev/null && apt-get install -y curl >/dev/null
fi

cd /tmp
echo "[SYS-METRIC] 下载 setup.sh..."
curl -u "${FTP_USER}:${FTP_PASSWORD}" "ftp://${FTP_HOST}:${FTP_PORT}/setup.sh" -o setup.sh

echo "[SYS-METRIC] 执行安装..."
chmod +x setup.sh
bash setup.sh --server "${FTP_HOST}" --user "${FTP_USER}" --password "${FTP_PASSWORD}" --port "${FTP_PORT}"

echo "[SYS-METRIC] 安装完成"
'

echo "[SYS-METRIC] Metric test node 安装流程完成"
