#!/usr/bin/bash
#
##
# Advanced Policy Firewall (APF) v2.0.2
#             (C) 2002-2026, R-fx Networks <proj@rfxn.com>
#             (C) 2026, Ryan MacDonald <ryan@rfxn.com>
# This program may be freely redistributed under the terms of the GNU GPL v2
##
#
CNF="/etc/apf/conf.apf"
if [ -f "$CNF" ]; then
   source "$CNF"
else
   echo "$CNF not found, aborting."
   exit 1
fi

if [ "$SET_VNET" == "0" ]; then
	exit 0
fi

if [ ! -f "$INSTALL_PATH/vnet/vnetgen.def" ]; then
        echo "vnetgen.def not found, aborting."
        exit 1
fi

# _vnet_create_rule: create a .rules file for an IP if it doesn't exist
_vnet_create_rule() {
        local addr="$1"
        if [ ! -f "$INSTALL_PATH/vnet/$addr.rules" ]; then
                command touch "$INSTALL_PATH/vnet/$addr.rules"
                command chmod 600 "$INSTALL_PATH/vnet/$addr.rules"
                . "$INSTALL_PATH/vnet/vnetgen.def"
        fi
}

if [ -z "$ip" ] && [ -z "$ifconfig" ]; then
        eout "{glob} ip and ifconfig not found; aborting"
	echo "ip and ifconfig not found; aborting"
        exit 1
elif [ -n "$ip" ]; then
 while IFS=' ' read -r _ _ _ addr _; do
  addr="${addr%%/*}"
  [ "$addr" == "127.0.0.1" ] && continue
  [ "$addr" == "$NET" ] && continue
  _vnet_create_rule "$addr"
 done < <($ip -o addr show "$IF" 2>/dev/null | grep -w inet)
elif [ -n "$ifconfig" ]; then
$ifconfig | grep -w "$IF" | awk '{print$1}' | while IFS= read -r iface; do
  $ifconfig "$iface" | grep -w inet | tr ':' ' ' | grep -vw "$NET" | awk '{print$3}' | while IFS= read -r addr; do
    _vnet_create_rule "$addr"
  done
done
fi


if [ "$SET_ADDIFACE" == "1" ]; then
 ## associate a vnet rule for ip's on additional interfaces other than the main
 if [ -n "$ip" ]; then
  $ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | sed 's/@.*//' | grep -vwE "lo|$IFACE_UNTRUSTED" | while IFS= read -r anet; do
   valtif=""; [[ ",$IFACE_TRUSTED," == *,"$anet",* ]] && valtif="$anet"
   if [ -z "$valtif" ]; then
    while IFS=' ' read -r _ _ _ addr _; do
     addr="${addr%%/*}"
     [ "$addr" == "127.0.0.1" ] && continue
     [ "$addr" == "$NET" ] && continue
     _vnet_create_rule "$addr"
    done < <($ip -o addr show "$anet" 2>/dev/null | grep -w inet)
   fi
  done
 elif [ -n "$ifconfig" ]; then
  $ifconfig | grep -E '^[a-zA-Z0-9]' | awk '{print$1}' | tr -d ':' | grep -vwE "lo|$IFACE_UNTRUSTED" | while IFS= read -r anet; do
   $ifconfig | grep -w "$anet" | awk '{print$1}' | while IFS= read -r iface; do
    valtif=""; [[ ",$IFACE_TRUSTED," == *,"$anet",* ]] && valtif="$anet"
    if [ -z "$valtif" ]; then
     $ifconfig "$iface" | grep -w inet | tr ':' ' ' | grep -vw "$NET" | awk '{print$3}' | while IFS= read -r addr; do
      _vnet_create_rule "$addr"
     done
    fi
   done
  done
 fi
fi
