#!/bin/bash
set -eo pipefail

# ipset-geoblock version 1.02
#
# Modified for ViciBox v.8.1
#
# Copyright (C) 2018  James Pearson <jamesp@vicidial.com>    LICENSE: AGPLv2
#
# Downloads the APNIC country IP delegation list and populates an IPSet
# with CIDRs for the configured blocked countries.
# Intended to run once at boot; country IP ranges change infrequently.
#
# Crontab: @reboot /usr/share/vicibox-firewall/ipset-geoblock >/dev/null 2>&1
#

# Default globals — override any of these in /etc/vicibox-geoblock.conf
LOCALCONF="/etc/vicibox-geoblock.conf"
BADCN=(CN VN RU IN AF UA TW TH SK SI RO PL PK PH LV LU ID HU HR BD)
IPSET_BIN="/usr/sbin/ipset"
FIREWALLD_BIN="/usr/bin/firewall-cmd"
AGGREGATE_BIN="/usr/bin/aggregate"
RULE='geoblock'
APNICLIST='/usr/share/vicibox-firewall/delegated-apnic-latest'
APNICURL='https://ftp.apnic.net/stats/apnic/delegated-apnic-latest'
PATH="/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin"
export PATH

# Load local config overrides if present
if [ -f "$LOCALCONF" ]; then
    . "$LOCALCONF"
fi

# Build an associative array for O(1) exact country code lookup.
# Done after config load so a custom $BADCN array is respected.
declare -A BADCN_SET
for cn in "${BADCN[@]}"; do BADCN_SET["$cn"]=1; done

# Convert an APNIC host count to a CIDR prefix length (log2 of count).
function range2nm() {
    local x=$1 l=-1
    while (( x )); do
        l=$(( l + 1 ))
        x=$(( x / 2 ))
    done
    echo $(( 32 - l ))
}

echo "  Generating Geo Block rules..."
echo "    Blocked Countries: ${BADCN[*]}"

# --- Sanity checks ---
if [ ! -x "$IPSET_BIN" ]; then
    echo "  $IPSET_BIN not found or not executable. Is ipset installed?"; exit 1
fi
if [ ! -x "$FIREWALLD_BIN" ]; then
    echo "  $FIREWALLD_BIN not found or not executable. Is firewalld installed?"; exit 1
fi
if [ ! -x "$AGGREGATE_BIN" ]; then
    echo "  $AGGREGATE_BIN not found or not executable. Is aggregate installed?"; exit 1
fi

# Create the geoblock ipset if it doesn't already exist
if ! "$IPSET_BIN" list "$RULE" >/dev/null 2>&1; then
    echo -n "  No $RULE IPSet found, creating... "
    "$IPSET_BIN" create "$RULE" hash:net --exist
    echo "done."
fi

# --- Download fresh APNIC delegation data ---
echo -n "    Downloading APNIC delegation list... "
if curl -sSf "$APNICURL" -o "$APNICLIST" 2>/dev/null; then
    echo "done."
else
    echo "warning: download failed, falling back to existing file."
    if [ ! -f "$APNICLIST" ]; then
        echo "  No APNIC delegation list at $APNICLIST and download failed. Exiting."
        exit 1
    fi
fi

# --- Create temp files safely ---
# trap ensures they are removed on any exit, including errors
CIDRTMP=$(mktemp /tmp/cidrtemp.XXXXXX)
AGGTMP=$(mktemp /tmp/aggtmpgeo.XXXXXX)
trap 'rm -f "$CIDRTMP" "$AGGTMP"' EXIT

# --- Parse APNIC delegation file ---
# Format: registry|cc|type|start|count|date|status
# We want ipv4 lines whose 2-letter country code is in the block list.
LINENUM=$(wc -l < "$APNICLIST")
echo -n "    Processing APNIC delegation list ($LINENUM entries)... "
while IFS='|' read -r _reg country type start count _rest; do
    # Only process IPv4 entries with a valid 2-letter country code
    [[ "$type"    == "ipv4" ]]        || continue
    [[ "$country" =~ ^[A-Z]{2}$ ]]   || continue
    [[ -n "${BADCN_SET[$country]+x}" ]] || continue
    echo "$start/$(range2nm "$count")" >> "$CIDRTMP"
done < "$APNICLIST"
LINENUM=$(wc -l < "$CIDRTMP")
echo "Found $LINENUM entries."

# --- Aggregate to reduce rule count ---
echo -n "    Aggregating list... "
"$AGGREGATE_BIN" -q -t < "$CIDRTMP" > "$AGGTMP"
LINENUM=$(wc -l < "$AGGTMP")
echo "now $LINENUM entries."

# --- Flush stale entries then load the new aggregated list ---
# Flush first so removed or changed countries don't leave orphaned rules.
echo -n "    Loading rules into $RULE... "
"$IPSET_BIN" flush "$RULE"
if "$FIREWALLD_BIN" --ipset="$RULE" --add-entries-from-file="$AGGTMP" >/dev/null 2>&1; then
    echo "done."
else
    echo "failed!"
    echo "  Error loading entries into IPSet $RULE. Check firewalld status."
    exit 1
fi

echo "  Finished!"
