#!/bin/bash

ASNS=(
	"AS32934:Meta"
	"AS8075:Microsoft"	
)

TMP_DIR="/tmp/asn-ipsets"
mkdir -p "$TMP_DIR"

for ENT in "${ASNS[@]}"; do
	ASN="${ENT%%:*}"
	DISP="${ENT##*:}"

	SET_NAME="$(echo "$DISP" | tr '[:upper:]' '[:lower:]')"
	TMP_FILE="$TMP_DIR/${SET_NAME}.txt"

	echo "Updating $DISP ($ASN)"

	# create if dont exist
	ipset list "$SET_NAME" >/dev/null 2>&1 || ipset create "$SET_NAME" hash:net

	# reach out to RADB for IP addresses
	whois -h whois.radb.net -- "-i origin $ASN" \
		| grep '^route:' \
		| awk '{print $2}' \
		| sort -u > "$TMP_FILE"

	# flush out old entries
	ipset flush "$SET_NAME"

	# add new ones in
	while read cidr; do
		ipset add "$SET_NAME" "$cidr" -exist
	done < "$TMP_FILE"
done

# save and forget
ipset save > /etc/ipset.conf
