#!/usr/bin/env bash
# Requires bash, curl and Python 3. Run server-side, never with shell tracing.
set -euo pipefail
: "${UKPT_API_KEY:?Set UKPT_API_KEY privately}"
base="${UKPT_API_URL:-https://api.ukpt.botric.co.uk}"
crs="${1:-PWY}"
python3 - "$base" "$crs" <<'PY'
import sys
from urllib.parse import urlsplit
url = urlsplit(sys.argv[1])
assert url.scheme == 'https' and url.netloc and not url.username and not url.password and url.path in ('', '/') and not url.query and not url.fragment, 'Use a plain HTTPS API origin'
assert len(sys.argv[2]) == 3 and sys.argv[2].isascii() and sys.argv[2].isalnum(), 'Use a CRS code'
PY
# Read headers through stdin so the private key is absent from curl's arguments.
request() {
  if [[ "$UKPT_API_KEY" == *$'\n'* || "$UKPT_API_KEY" == *$'\r'* || "$UKPT_API_KEY" == *'"'* || "$UKPT_API_KEY" == *'\'* ]]; then
    printf '%s\n' 'Invalid key format' >&2; return 1
  fi
  printf 'header = "X-API-Key: %s"\n' "$UKPT_API_KEY" | curl --config - --silent --show-error --fail --max-time 15 --proto '=https' --header 'Accept: application/json' "${base%/}$1"
  # Redirects are deliberately not followed. No rapid automatic retries.
}
station=$(request "/v1/resolve?crs=$crs")
id=$(python3 -c 'import json,sys; from urllib.parse import quote; print(quote(json.load(sys.stdin)["id"],safe=""))' <<< "$station")
printf '%s\n' "$station"
request "/v1/map/locations/$id/departures?limit=5"
printf '\n'
request "/v2/rail/stations/$crs/nearby-bus-services?distance=500&stop_limit=6&service_limit=30&include_calling_patterns=false"
printf '\n'
