#!/bin/sh
# Run the OSM taxiway export for one ICAO (osmium/ogr2ogr/jq over the aeroway PBF).
# Broker rules: `taxiways-export [A-Z]{4}` and `taxiways-export [A-Z]{4} <lat> <lon>` (six
# decimals each). With coordinates the export picks the airfield there instead of whatever
# carries the ICAO tag worldwide. Writes <ICAO>-taxiways.geojson into the osm-maps dir. This
# takes MINUTES on a cold cache.
#
# Everything is re-validated here (defence in depth — the allowlist already pins the shape,
# and the broker exec's us shell-free so no argument can be an operator).
set -eu
OSM_DIR=/osm-maps

icao="${1:-}"
case "$icao" in
    [A-Z][A-Z][A-Z][A-Z]) ;;
    *) echo "invalid ICAO: '$icao'" >&2; exit 2 ;;
esac

lat="${2:-}"
lon="${3:-}"
if [ -n "$lat$lon" ]; then
    for v in "$lat" "$lon"; do
        case "$v" in
            ''|*[!0-9.-]*) echo "invalid coordinate: '$v'" >&2; exit 2 ;;
        esac
    done
    awk -v a="$lat" -v o="$lon" 'BEGIN { exit !(a >= -90 && a <= 90 && o >= -180 && o <= 180) }' \
        || { echo "coordinates out of range: '$lat' '$lon'" >&2; exit 2; }
fi

cd "$OSM_DIR" 2>/dev/null || { echo "osm-maps dir not mounted at $OSM_DIR" >&2; exit 4; }
[ -x ./export-icao-geojson.sh ] || { echo "export-icao-geojson.sh missing in $OSM_DIR" >&2; exit 5; }

if [ -n "$lat$lon" ]; then
    exec ./export-icao-geojson.sh "$icao" "$lat" "$lon"
fi
exec ./export-icao-geojson.sh "$icao"
