#!/bin/bash

# update a predefined and explicitly supported set of dynamic nftables rules

# supported values must be passed as environment variable. They are:
#   - V2G_SERVER_TCP_PORTS
#   - VDV261_DESTINATIONS
#
# Note: if V2G_SERVER_TCP_PORTS is empty/missing, the script exits with failure

NFT_CMD="/usr/sbin/nft"
: "${V2G_SERVER_TCP_PORTS:=}"
: "${VDV261_DESTINATIONS:=}"

set -Eeuo pipefail

# Check that V2G_SERVER_TCP_PORTS is a valid list of ports
if echo "$V2G_SERVER_TCP_PORTS" | grep -qE '^[0-9]+((, |,)[0-9]+)*$'; then
  echo "open ingress TCP ports: $V2G_SERVER_TCP_PORTS"
else
  echo "ERROR: no or wrong ingress TCP port specified, exit.."
  exit 1
fi

# Check that VDV261_DESTINATIONS is a valid list of IPv6 addresses, simplified by only checking for allowed characters
if echo "$VDV261_DESTINATIONS" | grep -qE '^([0-9a-fA-F:]+)((, |,)[0-9a-fA-F:]+)*$'; then
  echo "allow VDV261 destinations: $VDV261_DESTINATIONS"
else
  VDV261_DESTINATIONS=
fi

# apply all dynamic rules in one go
$NFT_CMD -f - <<EOF
flush set ip6 allow_ccs_charge v2g_server_tcp_ports
flush set ip6 allow_ccs_charge vdv261_destinations


$( [[ -n "$V2G_SERVER_TCP_PORTS" ]] && echo "element ip6 allow_ccs_charge v2g_server_tcp_ports { $V2G_SERVER_TCP_PORTS }")
$( [[ -n "$VDV261_DESTINATIONS" ]] && echo "element ip6 allow_ccs_charge vdv261_destinations { $VDV261_DESTINATIONS }")
EOF
