#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

# Replaces the legal placeholder in the built Privacy Notice, rendered email
# footer examples, and the downloadable onboarding contract. The address is read
# only from CORPORATE_POSTAL_ADDRESS and is never printed.

BUILD_DIR="${1:-dist}"
PLACEHOLDER='[Insert Corporate Headquarters Address Here]'

fail() { echo "FAIL: $*" >&2; exit 1; }
command -v node >/dev/null 2>&1 || fail "node is required"
test -d "$BUILD_DIR" || fail "build directory does not exist: $BUILD_DIR"
test -n "${CORPORATE_POSTAL_ADDRESS:-}" || fail "CORPORATE_POSTAL_ADDRESS is required"
test "$CORPORATE_POSTAL_ADDRESS" != "$PLACEHOLDER" || fail "postal address is still the placeholder"
test "${#CORPORATE_POSTAL_ADDRESS}" -ge 12 || fail "postal address is implausibly short"
case "$CORPORATE_POSTAL_ADDRESS" in *$'\n'*|*$'\r'*) fail "postal address must be one line" ;; esac

export BUILD_DIR CORPORATE_POSTAL_ADDRESS PLACEHOLDER
node <<'NODE'
const fs = require('node:fs');
const path = require('node:path');

const root = path.resolve(process.env.BUILD_DIR);
const address = process.env.CORPORATE_POSTAL_ADDRESS;
const placeholder = process.env.PLACEHOLDER;
const htmlTargets = [
  path.join(root, 'privacy', 'index.html'),
  path.join(root, 'index.html'),
];
const jsonTargets = [
  path.join(root, 'assets', 'codecr-day2-executive-onboarding-sequence.json'),
];

const escapeHtml = (value) => value
  .replaceAll('&', '&amp;')
  .replaceAll('<', '&lt;')
  .replaceAll('>', '&gt;')
  .replaceAll('"', '&quot;')
  .replaceAll("'", '&#39;');

for (const file of [...htmlTargets, ...jsonTargets]) {
  if (!fs.existsSync(file)) throw new Error(`missing legal artifact: ${file}`);
}

for (const file of htmlTargets) {
  const source = fs.readFileSync(file, 'utf8');
  if (!source.includes(placeholder)) throw new Error(`placeholder not found: ${file}`);
  fs.writeFileSync(file, source.replaceAll(placeholder, escapeHtml(address)));
}

const replaceStrings = (value) => {
  if (typeof value === 'string') return value.replaceAll(placeholder, address);
  if (Array.isArray(value)) return value.map(replaceStrings);
  if (value && typeof value === 'object') {
    return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, replaceStrings(item)]));
  }
  return value;
};

for (const file of jsonTargets) {
  const source = fs.readFileSync(file, 'utf8');
  if (!source.includes(placeholder)) throw new Error(`placeholder not found: ${file}`);
  const hydrated = replaceStrings(JSON.parse(source));
  fs.writeFileSync(file, `${JSON.stringify(hydrated, null, 2)}\n`);
}

for (const file of [...htmlTargets, ...jsonTargets]) {
  if (fs.readFileSync(file, 'utf8').includes(placeholder)) {
    throw new Error(`placeholder remains: ${file}`);
  }
}
NODE

unset CORPORATE_POSTAL_ADDRESS
echo "PASS: legal address hydrated in three production artifacts; value was not printed."
