#!/bin/sh
set -eu

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

if [ ! -f "$ENV_FILE" ]; then
  echo "Missing $ENV_FILE. Run scripts/ensure-local-load-env.sh 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

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

NEW_METRICS_TOKEN=$new_metrics_token \
  perl -pe '
    s/^METRICS_TOKEN=.*/METRICS_TOKEN=$ENV{NEW_METRICS_TOKEN}/;
  ' "$ENV_FILE" >"$temporary"

if cmp -s "$ENV_FILE" "$temporary"; then
  echo "METRICS_TOKEN is missing from $ENV_FILE." >&2
  exit 1
fi

mv "$temporary" "$ENV_FILE"
chmod 600 "$ENV_FILE"
trap - EXIT HUP INT TERM

echo "The isolated load-profile metrics token was rotated without printing it."
