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

STACK_ENV="${1:-}"
if [[ -z "$STACK_ENV" ]]; then
  echo "Usage: $0 /path/to/stack.env" >&2
  exit 2
fi

mkdir -p "$(dirname "$STACK_ENV")"
touch "$STACK_ENV"

current_secret=""
if grep -q '^XMPP_SECRET=' "$STACK_ENV"; then
  current_secret="$(grep '^XMPP_SECRET=' "$STACK_ENV" | head -n1 | cut -d= -f2- | tr -d '"' | tr -d "'" | tr -d '\r' | tr -d '\n')"
fi

if [[ -n "$current_secret" ]]; then
  printf "%s" "$current_secret"
  exit 0
fi

generate_secret() {
  if command -v openssl >/dev/null 2>&1; then
    openssl rand -base64 48 | tr -d '\n'
    return 0
  fi
  if command -v python3 >/dev/null 2>&1; then
    python3 -c 'import secrets; print(secrets.token_urlsafe(48))'
    return 0
  fi
  head -c 48 /dev/urandom | base64 | tr -d '\n'
}

secret="$(generate_secret)"
if [[ -z "$secret" ]]; then
  echo "Failed to generate XMPP_SECRET." >&2
  exit 1
fi

tmp="$(mktemp)"
awk -v s="$secret" '
  BEGIN { done = 0 }
  /^XMPP_SECRET=/ {
    if (!done) {
      print "XMPP_SECRET=" s
      done = 1
    }
    next
  }
  { print }
  END {
    if (!done) print "XMPP_SECRET=" s
  }
' "$STACK_ENV" > "$tmp"
mv "$tmp" "$STACK_ENV"

printf "%s" "$secret"
