#!/bin/sh
# script/asupdate: rebuild the AS list built into RouteWatch from
# as.csv with cmd/asinfo-gen, which fails when it finds no AS. The new
# list replaces the old one only when the generator succeeds. Otherwise
# the old list stays as it was and the script exits non-zero.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"

AS_DATA="pkg/asinfo/asdata.json.gz"
# Next to AS_DATA, so the final mv is a rename on one file system.
AS_DATA_TMP="$AS_DATA.tmp"

main() {
    cd "$ROOT"

    json="$(mktemp)"
    trap 'rm -f "$json" "$AS_DATA_TMP"' EXIT
    # A signal exits through the EXIT trap too.
    trap 'exit 1' HUP INT TERM

    echo "Updating AS info data..."
    if ! go run ./cmd/asinfo-gen >"$json"; then
        echo "asupdate: the generator failed; $AS_DATA is unchanged" >&2
        exit 1
    fi

    # -n leaves the time out of the file, so an unchanged list gives the
    # same bytes.
    gzip -n -c <"$json" >"$AS_DATA_TMP"
    mv "$AS_DATA_TMP" "$AS_DATA"
}

main "$@"
