#!/bin/sh
set -eu

origin="${APP_PUBLIC_BASE_URL:-}"
case "$origin" in
  http://*|https://*) ;;
  *) echo "APP_PUBLIC_BASE_URL must be an HTTP(S) origin." >&2; exit 1 ;;
esac

authority="${origin#*://}"
authority="${authority%/}"
case "$authority" in
  ""|*/*|*\?*|*\#*|*@*) echo "APP_PUBLIC_BASE_URL must not contain credentials, a path, query, or fragment." >&2; exit 1 ;;
esac

external_host="${authority%%:*}"
port="${authority#"$external_host"}"
case "$external_host" in
  ""|*[!A-Za-z0-9.-]*) echo "APP_PUBLIC_BASE_URL contains an unsupported host." >&2; exit 1 ;;
esac
if [ -n "$port" ]; then
  port="${port#:}"
  case "$port" in ""|*[!0-9]*) echo "APP_PUBLIC_BASE_URL contains an invalid port." >&2; exit 1 ;; esac
fi

sed "s/__APP_EXTERNAL_HOST__/$external_host/g" \
  /etc/nginx/jobtracker.conf.template \
  > /etc/nginx/conf.d/default.conf
