#!/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_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
	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
	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
	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
