#!/bin/bash
set -euo pipefail

echo "[INFO] Starting Prometheus Targets Updater under supervisor..."

# 配置变量
PROMETHEUS_BASE_PATH=${PROMETHEUS_BASE_PATH:-/private/argus/metric/prometheus}
NODES_CONFIG_FILE=${NODES_CONFIG_FILE:-${PROMETHEUS_BASE_PATH}/nodes.json}
TARGETS_DIR=${PROMETHEUS_BASE_PATH}/targets
EXPORTER_CONFIG_FILE=${EXPORTER_CONFIG_FILE:-${PROMETHEUS_BASE_PATH}/exporter_config.json}
CHECK_INTERVAL=${CHECK_INTERVAL:-30}
LOG_LEVEL=${LOG_LEVEL:-INFO}

echo "[INFO] Prometheus base path: ${PROMETHEUS_BASE_PATH}"
echo "[INFO] Nodes config file: ${NODES_CONFIG_FILE}"
echo "[INFO] Targets directory: ${TARGETS_DIR}"
echo "[INFO] Exporter config file: ${EXPORTER_CONFIG_FILE}"
echo "[INFO] Check interval: ${CHECK_INTERVAL}s"
echo "[INFO] Log level: ${LOG_LEVEL}"

# 确保目录存在
mkdir -p "${TARGETS_DIR}"

# 检查 EXPORTER_CONFIG_FILE 是否存在，没有则从内部复制
if [ ! -f "${EXPORTER_CONFIG_FILE}" ]; then
    echo "[INFO] exporter_config.json not found at ${EXPORTER_CONFIG_FILE}, copying from internal location..."
    cp /usr/local/bin/exporter_config.json "${EXPORTER_CONFIG_FILE}"
    chown nobody:nogroup "${EXPORTER_CONFIG_FILE}"
    echo "[INFO] Successfully copied exporter_config.json to ${EXPORTER_CONFIG_FILE}"
else
    echo "[INFO] exporter_config.json already exists at ${EXPORTER_CONFIG_FILE}, skipping copy"
fi

exec python3 /usr/local/bin/update_targets.py \
    --config "${NODES_CONFIG_FILE}" \
    --targets-dir "${TARGETS_DIR}" \
    --exporter-config "${EXPORTER_CONFIG_FILE}" \
    --log-level "${LOG_LEVEL}" \
    --daemon \
    --check-interval "${CHECK_INTERVAL}"
