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

cd "$(dirname "$0")/.."

if [[ -f scripts/load-secrets.sh ]]; then
  source scripts/load-secrets.sh
fi

LOGGING_NAMESPACE="${LOGGING_NAMESPACE:-logging}"
LOGS_HOST="${LOGS_HOST:-logs.lomavuokraus.fi}"
GRAFANA_CLUSTER_ISSUER="${GRAFANA_CLUSTER_ISSUER:-letsencrypt-prod}"
: "${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD to provision Grafana.}"

HELM_BIN="${HELM_BIN:-$(command -v helm || true)}"

ensure_helm() {
  if [[ -n "$HELM_BIN" && -x "$HELM_BIN" ]]; then
    return
  fi
  echo "Helm not found, downloading to a temp dir..."
  TMP_DIR="$(mktemp -d)"
  curl -fsSL https://get.helm.sh/helm-v3.16.1-linux-amd64.tar.gz | tar -xz -C "$TMP_DIR"
  HELM_BIN="$TMP_DIR/linux-amd64/helm"
}

ensure_helm

echo "Using helm at: $HELM_BIN"

$HELM_BIN repo add grafana https://grafana.github.io/helm-charts
$HELM_BIN repo update

export LOGS_HOST GRAFANA_CLUSTER_ISSUER GRAFANA_ADMIN_PASSWORD

LOKI_TMP=$(mktemp)
PROMTAIL_TMP=$(mktemp)
GRAFANA_TMP=$(mktemp)

cat k8s/logging/loki-values.yaml >"$LOKI_TMP"
cat k8s/logging/promtail-values.yaml >"$PROMTAIL_TMP"
envsubst < k8s/logging/grafana-values.yaml >"$GRAFANA_TMP"

echo "Installing/Upgrading Loki..."
$HELM_BIN upgrade --install loki grafana/loki -n "$LOGGING_NAMESPACE" -f "$LOKI_TMP" --create-namespace

echo "Installing/Upgrading Promtail..."
$HELM_BIN upgrade --install promtail grafana/promtail -n "$LOGGING_NAMESPACE" -f "$PROMTAIL_TMP"

echo "Installing/Upgrading Grafana..."
$HELM_BIN upgrade --install grafana grafana/grafana -n "$LOGGING_NAMESPACE" -f "$GRAFANA_TMP"

echo "Resources in $LOGGING_NAMESPACE:"
kubectl get pods,svc,ingress -n "$LOGGING_NAMESPACE"

echo "Done. Grafana ingress host: https://${LOGS_HOST}"
