#!/bin/bash
# Update asn data
# The target file must be given as only argument on the commandline.
PATH=/bin:/usr/bin:/usr/local/bin

# set the http proxy here:
# export http_proxy=http://proxy.example.com:8080/
# export HTTPS_PROXY=https://proxy.example.com:8080/
# export FTP_PROXY=ftp://proxy.example.com:8080/

set -e
trap cleanup EXIT

fail()
{
  echo >&2 "$@"
  exit 23
}

setup()
{
  [ "$#" -eq 1 ] || fail "Exactly one argument DESTINATION-FILE must be given."
  DEST_FILE="$1"
  TMP_DIR=`mktemp -d`
  dest_dir=`dirname "$DEST_FILE"`
  [ -d "$dest_dir" ] || mkdir -p "$dest_dir"
}

cleanup()
{
  [ -d "$dest_dir" ] && rm -rf "$TMP_DIR"
}

fetch_and_install()
{
  cd "$TMP_DIR"
  # FIXME: we have to use http as the data is not available via https,
  # so this is not a secure connection... :-(
  curl -k -s -O http://data.ris.ripe.net/rrc12/latest-bview.gz
  pyasn_util_convert.py --single latest-bview.gz ipasn.dat \
                        --no-progress >/dev/null
  mv -f ipasn.dat "$DEST_FILE"
}

setup "$@"
fetch_and_install
