#!/bin/bash

# use 7 most recent routeviews prefix files
# remove too-short and too-long prefixes
# combine with the do-not-probe list
# save to a target file
# update symlink to point to new target file
# ark clients will fetch targets via https

set -e -u -o pipefail

DONOTPROBE=/etc/ark/badips.prefixes.aggr
PREP_DIR=/staging/prefix-probing.update-prep
TARGET_DIR=$PREP_DIR/targets
PREFIX_DIR=/data/routing/routeviews-prefix2as
PREFIX_LOG=$PREFIX_DIR/pfx2as-creation.log

mkdir -p $PREP_DIR
mkdir -p $TARGET_DIR

today=$(date -u +%F)

# combine the 7 most recent prefix files, excluding any too-short and
# too-long prefixes
cd $PREFIX_DIR
zcat $(tail -n 7 $PREFIX_LOG | cut -f 3) \
    | awk '$2 >= 8 && $2 <= 24 {printf "%s/%s\n", $1, $2}' \
    | sort \
    | uniq \
    > "$TARGET_DIR/$today.targets"

# new prefixes created, remove old prefix files
#find $INPUT_DIR/ -type f -name '*.prefixes.gz' -mtime +7 -delete

# append the do-not-probe list to the targets, any lines starting with a '-'
# will be excluded from probing by sc_prefixprober
sed 's/^/-/' "$DONOTPROBE" >> "$TARGET_DIR/$today.targets"

# new targets created, remove old target files
find $TARGET_DIR/ -type f -name '*.targets' -mtime +7 -delete

# update symlink to point to the newest targets list
ln -snf "$PREP_DIR/targets/$today.targets" "$PREP_DIR/targets/latest-target"
