#!/bin/sh
# Fetch a boundary file!
# # Author: Dan Jacobson https://www.jidanni.org/
# Copyright: https://www.gnu.org/licenses/gpl.html
# Created: 2023-09-04
# Last-Updated: 2024-05-13T20:29:45+0000
#     Update #: 16

# Here we use a site where getting a boundary is less hassle.

if test $# -lt 1
then echo usage: $0 osm_relation_id [output file] 1>&2; exit 32
fi
osm_relation_id=$1
case $osm_relation_id in
    [0-9]*[0-9]);;
    *) echo \$$osm_relation_id should be all digits. 1>&2; exit 64;;
esac
if test $# -eq 2
then o=$2 #use "-" for stdout
else o=$1.kml #default output
fi
set -ue
mapit_id=$(
    curl --silent --fail-with-body --show-error --location \
         https://global.mapit.mysociety.org/code/osm_rel/$osm_relation_id |
        perl -nwle '/\d+/ && print $&;')
case $mapit_id in
    [0-9]*[0-9]);;
    *) echo \$$mapit_id should be all digits. 1>&2; exit 66;;
esac
curl --silent --fail-with-body --show-error -o $o \
     https://global.mapit.mysociety.org/area/$mapit_id.kml