#!/bin/sh
# This file is heavily based on code from https://github.com/Xentrk/netflix-vpn-bypass/blob/master/IPSET_Netflix.sh

TARGET_INTERFACE='wan'
TARGET_NFTSET_4="pbr_${TARGET_INTERFACE}_4_dst_ip_user"
TARGET_NFTSET_6="pbr_${TARGET_INTERFACE}_6_dst_ip_user"
TARGET_IPSET_4="pbr_${TARGET_INTERFACE}_4_dst_net_user"
TARGET_IPSET_6="pbr_${TARGET_INTERFACE}_6_dst_net_user"
TARGET_TABLE='inet fw4'
TARGET_URL="https://ip-ranges.amazonaws.com/ip-ranges.json"
TARGET_DL_FILE_4="/var/pbr_tmp_aws_ip_ranges.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_aws_ip_ranges.ipv6"
_ret=0

if [ ! -s "$TARGET_DL_FILE_4" ]; then
	uclient-fetch --no-check-certificate -qO- "$TARGET_URL" 2>/dev/null | grep "ip_prefix" | sed 's/^.*\"ip_prefix\": \"//; s/\",//' > "$TARGET_DL_FILE_4"
fi
if [ -s "$TARGET_DL_FILE_4" ]; then
	if [ -n "$nft" ] && [ -x "$nft" ]; then
		while read -r p; do "$nft" "add element $TARGET_TABLE $TARGET_NFTSET_4 { $p }" || _ret=1; done < "$TARGET_DL_FILE_4"
	elif ipset -q list "$TARGET_IPSET_4" >/dev/null 2>&1; then
		if awk -v ipset="$TARGET_IPSET_4" '{print "add " ipset " " $1}' "$TARGET_DL_FILE_4" | ipset restore -!; then
			_ret=0
		else
			_ret=1
		fi
	fi
fi

if [ -n "$TARGET_DL_FILE_6" ] && [ ! -s "$TARGET_DL_FILE_6" ]; then
	uclient-fetch --no-check-certificate -qO- "$TARGET_URL" 2>/dev/null | grep "ipv6_prefix" | sed 's/^.*\"ipv6_prefix\": \"//; s/\",//' > "$TARGET_DL_FILE_6"
fi
if [ -s "$TARGET_DL_FILE_6" ]; then
	if [ -n "$nft" ] && [ -x "$nft" ]; then
		while read -r p; do "$nft" "add element $TARGET_TABLE $TARGET_NFTSET_6 { $p }" || _ret=1; done < "$TARGET_DL_FILE_6"
	elif ipset -q list "$TARGET_IPSET_6" >/dev/null 2>&1; then
		if awk -v ipset="$TARGET_IPSET_6" '{print "add " ipset " " $1}' "$TARGET_DL_FILE_6" | ipset restore -!; then
			_ret=0
		else
			_ret=1
		fi
	fi
fi

return $_ret
