#!/bin/sh
set -eu

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
ENV_FILE="$ROOT/.env"

if [ ! -f "$ENV_FILE" ]; then
  echo "Missing $ENV_FILE. Copy .env.example to .env first." >&2
  exit 1
fi

for command in openssl perl; do
  if ! command -v "$command" >/dev/null 2>&1; then
    echo "Required command is unavailable: $command" >&2
    exit 1
  fi
done

current=$(
  perl -ne '
    if (/^METRICS_TOKEN=(.*)$/) {
      print $1;
      exit;
    }
  ' "$ENV_FILE"
)

if [ -n "$current" ]; then
  chmod 600 "$ENV_FILE"
  echo "METRICS_TOKEN already exists; no secret was changed."
  exit 0
fi

new_metrics_token=$(openssl rand -hex 32)
tmp_env=$(mktemp "${ENV_FILE}.metrics.XXXXXX")
trap 'rm -f "$tmp_env"' EXIT HUP INT TERM
chmod 600 "$tmp_env"

NEW_METRICS_TOKEN=$new_metrics_token perl -0pe '
  if (s/^METRICS_TOKEN=.*$/METRICS_TOKEN=$ENV{NEW_METRICS_TOKEN}/m) {
    $replaced = 1;
  }

  END {
    print "\nMETRICS_TOKEN=$ENV{NEW_METRICS_TOKEN}\n" unless $replaced;
  }
' "$ENV_FILE" >"$tmp_env"

mv "$tmp_env" "$ENV_FILE"
chmod 600 "$ENV_FILE"
trap - EXIT HUP INT TERM
unset new_metrics_token

echo "Generated METRICS_TOKEN in the ignored .env without printing it."
