#!/bin/bash
# Updates the Recorded Future Risk list (uses the large list)
# The target file must be given as only argument on the commandline.
PATH=/bin:/usr/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 your API Token here
APITOKEN=""

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"
  echo "Downloading large ip risklist, this may take some time..."
  STATUSCODE=$(curl -H "X-RFToken: $APITOKEN" --write-out %{http_code} --silent --output rfiprisk.dat.gz "https://api.recordedfuture.com/v2/ip/risklist?format=csv%2Fsplunk&gzip=true&list=large")
  [ "$STATUSCODE" == "200" ] || fail "Error getting risklist, current list not updated: HTTP GET returned $STATUSCODE"
  gunzip rfiprisk.dat.gz
  mv -f rfiprisk.dat "$DEST_FILE"
}

[ "$APITOKEN" != "" ] || fail "Please update script with API token from Recorded Future."

setup "$@"
fetch_and_install
