#!/bin/sh
# This file is heavily based on code from https://github.com/Xentrk/netflix-vpn-bypass/blob/master/IPSET_Netflix.sh
# Credits to https://forum.openwrt.org/u/dscpl for api.hackertarget.com code.
# Credits to https://github.com/kkeker and https://github.com/tophirsch for api.bgpview.io code.

TARGET_INTERFACE='wan'
TARGET_NFTSET_4="pbr_${TARGET_INTERFACE}_4_dst_ip_user"
TARGET_NFTSET_6="pbr_${TARGET_INTERFACE}_6_dst_ip_user"
TARGET_TABLE='inet fw4'
TARGET_ASN='2906'
TARGET_DL_FILE_4="/var/pbr_tmp_AS${TARGET_ASN}.ipv4"
# Uncomment the following line if you enabled ipv6 for pbr and want IPv6 entries added to the IPv6 set
# TARGET_DL_FILE_6="/var/pbr_tmp_AS${TARGET_ASN}.ipv6"
DB_SOURCE='ipinfo.io'
#DB_SOURCE='api.hackertarget.com'
#DB_SOURCE='api.bgpview.io'
REGEX_IPV4='[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\/[0-9]\{1,\}'
REGEX_IPV6='.*::.*'
_ret=0

if [ ! -s "$TARGET_DL_FILE_4" ]; then
	if [ "$DB_SOURCE" = "ipinfo.io" ]; then
		TARGET_URL="https://ipinfo.io/AS${TARGET_ASN}"
		uclient-fetch --no-check-certificate -qO- "$TARGET_URL" 2>/dev/null | sed -n "s|\(.*\)/AS${TARGET_ASN}/\($REGEX_IPV4\)\"|\2|p" > "$TARGET_DL_FILE_4"
	fi
	if [ "$DB_SOURCE" = "api.hackertarget.com" ]; then
		TARGET_URL="https://api.hackertarget.com/aslookup/?q=AS${TARGET_ASN}"
		uclient-fetch --no-check-certificate -qO- "$TARGET_URL" 2>/dev/null | sed '1d' > "$TARGET_DL_FILE_4"
	fi
	if [ "$DB_SOURCE" = "api.bgpview.io" ]; then
		TARGET_URL="https://api.bgpview.io/asn/${TARGET_ASN}/prefixes"
		uclient-fetch --no-check-certificate -qO- "$TARGET_URL" 2>/dev/null | jsonfilter -e '@.data.ipv4_prefixes[*].prefix' > "$TARGET_DL_FILE_4"
	fi
fi

if [ -s "$TARGET_DL_FILE_4" ]; then
	params=
	while read -r p; do params="${params:+${params}, }${p}"; done < "$TARGET_DL_FILE_4"
	[ -n "$params" ] && nft "add element $TARGET_TABLE $TARGET_NFTSET_4 { $params }" || _ret=1
fi

if [ -n "$TARGET_DL_FILE_6" ] && [ ! -s "$TARGET_DL_FILE_6" ]; then
	if [ "$DB_SOURCE" = "ipinfo.io" ]; then
		TARGET_URL="https://ipinfo.io/AS${TARGET_ASN}"
		uclient-fetch --no-check-certificate -qO- "$TARGET_URL" 2>/dev/null | sed -n "s|\(.*\)/AS${TARGET_ASN}/\($REGEX_IPV6\)\"|\2|p" > "$TARGET_DL_FILE_6"
	fi
fi
if [ -s "$TARGET_DL_FILE_6" ]; then
	params=
	while read -r p; do params="${params:+${params}, }${p}"; done < "$TARGET_DL_FILE_6"
	[ -n "$params" ] && nft "add element $TARGET_TABLE $TARGET_NFTSET_6 { $params }" || _ret=1
fi

return $_ret
