#!/bin/sh

# Logging the entry point for debugging
logger -t route-fix-iface "Event: $INTERFACE dev=$DEVICE action=$ACTION"

if [ "$ACTION" = "ifup" ] && [ "$INTERFACE" = "wwan" ]; then
    # Fetch gateway from UCI
    GATEWAY=$(uci -q get network."${INTERFACE}".gateway)

    # Validation: Ensure GATEWAY isn't empty before proceeding
    if [ -z "$GATEWAY" ]; then
        logger -t route-fix-iface "Error: No gateway defined in config for $INTERFACE"
        exit 0
    fi

    # Check if the exact route already exists
    if ! ip route show default dev "$DEVICE" | grep -q "via $GATEWAY"; then

        # Remove any existing default routes for this device to prevent "File exists" errors
        ip route del default dev "$DEVICE" 2>/dev/null

        # Add the new route
        ip route add default via "$GATEWAY" dev "$DEVICE"

        if [ $? -eq 0 ]; then
            logger -t route-fix-iface "Successfully added default route via $GATEWAY on $DEVICE"
        else
            logger -t route-fix-iface "Failed to add route via $GATEWAY (RC: $?)"
        fi
    else
        logger -t route-fix-iface "Correct route already exists. No action taken."
    fi
fi