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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
env_file="$repo_root/.env"
gitignore_file="$repo_root/.gitignore"

if [[ -f "$env_file" ]] && grep -q -- "-----BEGIN PRIVATE KEY-----" "$env_file"; then
  echo "ERROR: .env must not contain a multi-line PEM private key; put it under config/ and reference WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE." >&2
  exit 1
fi

if [[ -f "$env_file" ]] && ! grep -q '^WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE=' "$env_file"; then
  echo "ERROR: .env must reference WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE." >&2
  exit 1
fi

if ! grep -Eq '(^|/)config/\*\.pem$' "$gitignore_file"; then
  echo "ERROR: .gitignore must ignore config/*.pem secret files." >&2
  exit 1
fi

make --dry-run --always-make -C "$repo_root" dev DEV_SERVICES="backend adminfront" >/dev/null
