#! /bin/bash
# Narrow IPv4 example for traffic originating on this server.
# Separate routing stage: its service requires successful firewall startup.
# A direct manual invocation does not enforce that service dependency.
# One directly attached subnet, one gateway, and one dedicated routing table.
# Run one instance at a time; no other service may manage this table/priority.
# This is not a forwarding, VPN, VRF, or multipath example.
export LC_ALL=C

# Fill in and review every value. Do not copy another server's settings.
CONFIGURATION_REVIEWED=no
SOURCE_IP=''       # Address already assigned to this server's interface
LINK_PREFIX=''     # Canonical directly attached subnet, such as a.b.c.0/24
GATEWAY=''         # A different, directly reachable router in that subnet
INTERFACE=''       # Actual outgoing interface name
TABLE_ID=''        # Dedicated numeric table ID, 1-252 in this example
RULE_PRIORITY=''   # Unused priority, 1-32765; review existing policy order

fail() {
    printf '%s\n' "$2" >&2
    exit "$1"
}

run() {
    "$@" || {
        status=$?
        fail "$status" "Failed ($status): $*"
    }
}

if [ "$CONFIGURATION_REVIEWED" != yes ]; then
    fail 1 'Configure and review the network settings before running this sample.'
fi
for value in "$SOURCE_IP" "$LINK_PREFIX" "$GATEWAY" "$INTERFACE"; do
    case "$value" in
        ''|*[[:space:]]*) fail 1 'Network settings must be filled in without whitespace.' ;;
    esac
done
for value in "$TABLE_ID" "$RULE_PRIORITY"; do
    case "$value" in
        ''|0*|*[!0-9]*) fail 1 'Use positive decimal IDs without leading zeros.' ;;
    esac
    [ "${#value}" -le 5 ] || fail 1 'ID is outside this example range.'
done
[ "$TABLE_ID" -le 252 ] || fail 1 'Choose a dedicated table ID from 1 through 252.'
[ "$RULE_PRIORITY" -le 32765 ] || fail 1 'Choose a priority from 1 through 32765.'
[ "$SOURCE_IP" != "$GATEWAY" ] || fail 1 'Source and gateway must differ in this example.'

# Read everything before making any changes; failures stop the script.
addresses=$(ip -4 -o address show dev "$INTERFACE") || {
    status=$?; fail "$status" 'Could not inspect the interface addresses.'
}
source_found=no
while read -r -a fields; do
    for ((i=0; i<${#fields[@]}-1; i++)); do
        if [ "${fields[i]}" = inet ] && [ "${fields[i+1]%/*}" = "$SOURCE_IP" ]; then
            source_found=yes
        fi
    done
done <<< "$addresses"
[ "$source_found" = yes ] || fail 1 'SOURCE_IP is not assigned to INTERFACE.'

rules=$(ip -4 -N rule show) || {
    status=$?; fail "$status" 'Could not inspect routing rules.'
}
rule_count=0
while read -r priority from source lookup table extra; do
    if [ "$priority" = "$RULE_PRIORITY:" ]; then
        [ "$from" = from ] && [ "$lookup" = lookup ] &&
        [ "$table" = "$TABLE_ID" ] && [ -z "$extra" ] || fail 1 'Rule priority conflict.'
        case "$source" in
            "$SOURCE_IP"|"$SOURCE_IP/32") ;;
            *) fail 1 'Source address conflicts at the chosen priority.' ;;
        esac
        rule_count=$((rule_count + 1))
    else
        # Conservatively refuse any other rule referencing this table.
        case " $priority $from $source $lookup $table $extra " in
            *" lookup $TABLE_ID "*) fail 1 'Another rule already uses this table.' ;;
        esac
    fi
done <<< "$rules"
[ "$rule_count" -le 1 ] || fail 1 'Duplicate rules exist at the chosen priority.'

# An unused table may not exist yet. Inspect all tables first so an error
# querying a particular table is never mistaken for an empty table.
all_routes=$(ip -4 -N -o route show table all) || {
    status=$?; fail "$status" 'Could not inspect routing tables.'
}
table_present=no
while read -r line; do
    case " $line " in
        *" table $TABLE_ID "*) table_present=yes ;;
    esac
done <<< "$all_routes"
routes=''
if [ "$table_present" = yes ]; then
    routes=$(ip -4 -o route show table "$TABLE_ID") || {
        status=$?; fail "$status" 'Could not inspect the dedicated table.'
    }
fi
link_count=0
default_count=0
while read -r line; do
    # Exact, deliberately conservative comparisons: unfamiliar attributes
    # require review rather than silently replacing an existing route.
    case "$line" in
        '') ;;
        "$LINK_PREFIX dev $INTERFACE scope link") link_count=$((link_count + 1)) ;;
        "default via $GATEWAY dev $INTERFACE") default_count=$((default_count + 1)) ;;
        *) fail 1 "Unexpected route in dedicated table: $line" ;;
    esac
done <<< "$routes"
[ "$link_count" -le 1 ] && [ "$default_count" -le 1 ] || fail 1 'Duplicate routes found.'

# Confirm manually that LINK_PREFIX is the actual attached subnet and
# GATEWAY is reachable on it; command success is not a connectivity test.
# Populate routes before installing the rule that selects this table.
if [ "$link_count" -eq 0 ]; then
    run ip -4 route add "$LINK_PREFIX" dev "$INTERFACE" scope link table "$TABLE_ID"
fi
if [ "$default_count" -eq 0 ]; then
    run ip -4 route add default via "$GATEWAY" dev "$INTERFACE" table "$TABLE_ID"
fi
if [ "$rule_count" -eq 0 ]; then
    run ip -4 rule add priority "$RULE_PRIORITY" from "$SOURCE_IP/32" lookup "$TABLE_ID"
fi

# Request invalidation of cached IPv4 routing state
run ip -4 route flush cache

# Reached only if all required commands succeeded. No automatic rollback.
exit 0
