#!/command/with-contenv /bin/bash
# shellcheck shell=bash
# shellcheck disable=SC1091,SC1090
# ================================
# Grafana longrun service
# ================================

SCRIPT_ROOT=/etc/s6-overlay/scripts
source "$SCRIPT_ROOT/base.sh"
# The config should be ready before starting
source "$GPUSTACK_OBSERVABILITY_CONFIG"
source "$SCRIPT_ROOT/default-variables.sh"

set -e

exec 2>&1

createDir "$GF_PATHS_DATA"
createDir "$GF_PATHS_LOGS"
createDir "$GF_PATHS_PLUGINS"

GRAFANA_CONFIG_DIR="$(dirname "$GF_PATHS_CONFIG")"
createDir "$GRAFANA_CONFIG_DIR"

if [ -f "$GF_PATHS_CONFIG" ]; then
    echo "[INFO] Using existing Grafana config at $GF_PATHS_CONFIG."
fi

export GF_PATHS_DATA
export GF_PATHS_LOGS
export GF_PATHS_PLUGINS
export GF_PATHS_PROVISIONING
export GF_PATHS_CONFIG
export GF_SERVER_HTTP_PORT
export GF_SERVER_ROOT_URL
export GF_SERVER_SERVE_FROM_SUB_PATH
export GF_SECURITY_ADMIN_USER
export GF_SECURITY_ADMIN_PASSWORD
export GF_AUTH_ANONYMOUS_ENABLED
export GF_AUTH_ANONYMOUS_ORG_ROLE
export GF_AUTH_DISABLE_LOGIN_FORM

echo "[INFO] Starting Grafana."
exec /usr/local/bin/grafana-server \
    --homepath /opt/grafana \
    --config "$GF_PATHS_CONFIG" \
    --packaging=gpustack
