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

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
primary_domain=${1:-}
staging_domain=${2:-}
target=${3:-"$ROOT/.env.edge"}

if [[ -z "$primary_domain" || -z "$staging_domain" ]]; then
  echo "Usage: $0 PRIMARY_DOMAIN STAGING_DOMAIN [OUTPUT_FILE]" >&2
  exit 1
fi

if [[ "$target" != /* ]]; then
  target="$ROOT/$target"
fi

if [[ -e "$target" ]]; then
  echo "Refusing to overwrite existing edge environment: $target" >&2
  exit 1
fi

target_dir=$(dirname -- "$target")
if [[ ! -d "$target_dir" ]]; then
  echo "Output directory does not exist: $target_dir" >&2
  exit 1
fi

tmp=$(mktemp "$target_dir/.edge-env.XXXXXX")
trap 'rm -f "$tmp"' EXIT HUP INT TERM
chmod 600 "$tmp"

PRIMARY_DOMAIN_VALUE=$primary_domain \
STAGING_DOMAIN_VALUE=$staging_domain \
  awk '
    BEGIN {
      replacement["PRIMARY_DOMAIN"] = ENVIRON["PRIMARY_DOMAIN_VALUE"]
      replacement["STAGING_DOMAIN"] = ENVIRON["STAGING_DOMAIN_VALUE"]
    }
    {
      separator = index($0, "=")
      key = separator > 1 ? substr($0, 1, separator - 1) : ""

      if (key in replacement) {
        print key "=" replacement[key]
      } else {
        print
      }
    }
  ' "$ROOT/.env.edge.example" >"$tmp"

mv "$tmp" "$target"
chmod 600 "$target"
trap - EXIT HUP INT TERM

"$ROOT/scripts/validate-edge-env.sh" "$target"
echo "Created mode-0600 edge environment: $target"
