#!/bin/sh
set -eu

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

if [ ! -f "$ENV_FILE" ]; then
  echo "Missing $ENV_FILE. Copy .env.example to .env first." >&2
  exit 1
fi

if ! command -v perl >/dev/null 2>&1; then
  echo "Required command is unavailable: perl" >&2
  exit 1
fi

set -a
# shellcheck source=/dev/null
. "$ENV_FILE"
set +a

if [ -n "${WNH_BASE_URL:-}" ]; then
  chmod 600 "$ENV_FILE"
  echo "WNH_BASE_URL already exists; no configuration was changed."
  exit 0
fi

: "${PHX_HOST:?PHX_HOST is missing from .env}"
: "${PHX_SCHEME:?PHX_SCHEME is missing from .env}"
: "${PHX_URL_PORT:?PHX_URL_PORT is missing from .env}"

if [ "$PHX_SCHEME" != https ]; then
  echo "A public Android origin requires PHX_SCHEME=https." >&2
  exit 1
fi

case "$PHX_HOST" in
  "" | *[!A-Za-z0-9.-]*)
    echo "PHX_HOST is not a supported public DNS hostname." >&2
    exit 1
    ;;
esac

case "$PHX_URL_PORT" in
  "" | *[!0-9]*)
    echo "PHX_URL_PORT must be a numeric HTTPS port." >&2
    exit 1
    ;;
esac

if [ "$PHX_URL_PORT" = 443 ]; then
  public_origin="https://$PHX_HOST"
else
  public_origin="https://$PHX_HOST:$PHX_URL_PORT"
fi

tmp_env=$(mktemp "${ENV_FILE}.public-origin.XXXXXX")
trap 'rm -f "$tmp_env"' EXIT HUP INT TERM
chmod 600 "$tmp_env"

WNH_PUBLIC_ORIGIN=$public_origin perl -0pe '
  END {
    print "\nWNH_BASE_URL=$ENV{WNH_PUBLIC_ORIGIN}\n";
  }
' "$ENV_FILE" >"$tmp_env"

mv "$tmp_env" "$ENV_FILE"
chmod 600 "$ENV_FILE"
trap - EXIT HUP INT TERM
unset public_origin

echo "Configured WNH_BASE_URL from the existing HTTPS Phoenix origin."
