#!/bin/bash
set -euo pipefail

echo "[INFO] Starting Grafana under supervisor..."

DOMAIN=grafana.metric.argus.com

# 记录容器 IP
IP=$(ifconfig | awk '/inet / && $2 != "127.0.0.1" {print $2; exit}')
echo "current IP: ${IP}"
echo "${IP}" > /private/argus/etc/${DOMAIN}
chmod +x /private/argus/etc/${DOMAIN}

# 确保必要目录存在（权限已在 Dockerfile 中设置）
mkdir -p /private/argus/metric/grafana/data
mkdir -p /private/argus/metric/grafana/logs
mkdir -p /private/argus/metric/grafana/plugins
mkdir -p /private/argus/metric/grafana/provisioning/datasources
mkdir -p /private/argus/metric/grafana/provisioning/dashboards
mkdir -p /private/argus/metric/grafana/data/sessions
mkdir -p /private/argus/metric/grafana/data/dashboards
mkdir -p /private/argus/metric/grafana/config
mkdir -p /var/log/grafana
mkdir -p /etc/grafana/provisioning/datasources
mkdir -p /var/lib/grafana

# 复制主配置文件到持久化目录
if [ -f "/tmp/grafana.ini" ]; then
    echo "[INFO] Copying grafana.ini to /private/argus/metric/grafana/config/"
    cp /tmp/grafana.ini /private/argus/metric/grafana/config/grafana.ini
    echo "[INFO] Grafana configuration copied successfully"
fi

# 检查配置文件来源（优先级：挂载目录 > 容器内配置 > 默认配置）
if [ -f "/private/argus/metric/grafana/config/grafana.ini" ]; then
    echo "[INFO] Using grafana.ini from /private/argus/metric/grafana/config/"
    CONFIG_FILE="--config=/private/argus/metric/grafana/config/grafana.ini"
elif [ -f "/etc/grafana/grafana.ini" ]; then
    echo "[INFO] Using custom grafana.ini from /etc/grafana/"
    CONFIG_FILE="--config=/etc/grafana/grafana.ini"
else
    echo "[INFO] Using default configuration"
    CONFIG_FILE=""
fi

# 复制数据源配置文件到挂载目录
DS_OUT="/private/argus/metric/grafana/provisioning/datasources/datasources.yml"
PROM_DOMAIN="prom.metric.argus.com:9090"

if [ -f "/tmp/datasources.yml" ] && [ ! -f "$DS_OUT" ]; then
    echo "[INFO] Initializing datasource provisioning file from /tmp"
    cp /tmp/datasources.yml "$DS_OUT"
fi

# 统一将数据源 URL 规范为 prom.metric.argus.com:9090
if [ -f "$DS_OUT" ]; then
    sed -i -E "s#^\s*url:\s*http://[^[:space:]]+#    url: http://$PROM_DOMAIN#g" "$DS_OUT" || true
    echo "[INFO] Datasource URL normalized to http://$PROM_DOMAIN"
elif [ -d "/etc/grafana/provisioning/datasources" ] && [ "$(ls -A /etc/grafana/provisioning/datasources)" ]; then
    echo "[INFO] Found datasource provisioning files in /etc/grafana/provisioning/datasources"
    # 确保数据源配置目录权限正确
    chown -R grafana:grafana /etc/grafana/provisioning/datasources
else
    echo "[INFO] No datasource provisioning files found, using manual configuration"
fi

# 复制仪表板配置文件到挂载目录
if [ -f "/tmp/dashboards.yml" ]; then
    echo "[INFO] Copying dashboard configuration to /private/argus/metric/grafana/provisioning/dashboards/"
    cp /tmp/dashboards.yml /private/argus/metric/grafana/provisioning/dashboards/dashboards.yml
    echo "[INFO] Dashboard configuration copied successfully"
fi

# 复制默认仪表板到挂载目录（按需，不覆盖已存在文件）
copy_dashboard_if_missing() {
    local src="$1"; local dst_name="$2"
    local dst_dir="/private/argus/metric/grafana/provisioning/dashboards"
    local dst="$dst_dir/$dst_name"
    if [ -f "$src" ]; then
        if [ ! -f "$dst" ]; then
            echo "[INFO] Installing dashboard: $dst_name"
            cp "$src" "$dst"
        else
            echo "[INFO] Dashboard exists, skip: $dst_name"
        fi
    fi
}

copy_dashboard_if_missing "/tmp/default_dashboard.json" "default_dashboard.json"
copy_dashboard_if_missing "/tmp/default_cluster_dashboard.json" "default_cluster_dashboard.json"
copy_dashboard_if_missing "/tmp/default_dashboard_by_instance.json" "default_dashboard_by_instance.json"

# 规范面板中的数据源字段：将字符串 "prometheus" 替换为 null（使用默认数据源）
DB_DIR="/private/argus/metric/grafana/provisioning/dashboards"
if [ -d "$DB_DIR" ]; then
  for f in "$DB_DIR"/*.json; do
    [ -f "$f" ] || continue
    sed -i -E 's/"datasource"\s*:\s*"prometheus"/"datasource": null/g' "$f" || true
  done
  echo "[INFO] Normalized dashboard datasource to default (null)"
fi

# 启动 Grafana
if [ -n "$CONFIG_FILE" ]; then
    echo "[INFO] Starting Grafana with custom configuration..."
    exec /usr/share/grafana/bin/grafana server \
        --homepath=/usr/share/grafana \
        --packaging=docker \
        $CONFIG_FILE
else
    echo "[INFO] Starting Grafana with default configuration..."
    exec /usr/share/grafana/bin/grafana server \
        --homepath=/usr/share/grafana \
        --packaging=docker \
        cfg:default.log.mode=console \
        cfg:default.log.level=info
fi
