#!/bin/sh
# shellcheck disable=SC2015,SC3003,SC3060
TARGET_URL='https://ip-ranges.amazonaws.com/ip-ranges.json'
TARGET_DL_FILE='/var/pbr_tmp_aws_ip_ranges.gz'
TARGET_TABLE='inet fw4'
TARGET_INTERFACE='wan'

_ret=1

mkdir -p "${TARGET_DL_FILE%/*}"

[ -s "$TARGET_DL_FILE" ] || \
	uclient-fetch --no-check-certificate -qO- "$TARGET_URL" | \
		gzip > "$TARGET_DL_FILE"

[ -s "$TARGET_DL_FILE" ] || return 1

[ "$(uci get pbr.config.ipv6_enabled)" = "1" ] && vers="4 6" || vers="4"
for ver in $vers;do
	case "$ver" in
		4) search='@.prefixes[*].ip_prefix';;
		6) search='@.ipv6_prefixes[*].ipv6_prefix';;
	esac
	params="$(zcat "$TARGET_DL_FILE" | jsonfilter -e "$search")"
	[ -n "$params" ] && _ret=0 || continue
	nftset="pbr_${TARGET_INTERFACE}_${ver}_dst_ip_user"
	nft "add element $TARGET_TABLE $nftset { ${params//$'\n'/, } }" || _ret=1
done

return $_ret
