#! /bin/bash

# Adapted from https://github.com/natecarlson/quectel-rgmii-configuration-notes/blob/main/files/ttl-override
# Uses ttlvalue file to read what ttl should be set to


if [ -f /usrdata/simplefirewall/ttlvalue ];
then
	ttlfile=$(</usrdata/simplefirewall/ttlvalue)
    TTLVALUE=$(echo $ttlfile | grep -o "[0-9]\{1,3\}")
    
    if [ -z "${TTLVALUE}" ]; then
        echo "Couldnt get proper ttl value from file" >&2
        exit 1
    fi
else
    # Couldnt find ttlvalue file, lets generate one with 0 ttlvalue (0 = disabled)
    touch /usrdata/simplefirewall/ttlvalue && echo '0' > /usrdata/simplefirewall/ttlvalue
    exit 1
fi

case "$1" in
start)
    if (( $TTLVALUE > 0 )); then
        echo "Adding TTL override rules: "
        iptables -t mangle -I POSTROUTING -o rmnet+ -j TTL --ttl-set ${TTLVALUE}
        ip6tables -t mangle -I POSTROUTING -o rmnet+ -j HL --hl-set ${TTLVALUE}
    else
        echo "TTLVALUE set to 0, nothing to do..."
    fi
    echo "done"
    ;;
  stop)
    if (( $TTLVALUE > 0 )); then
        echo "Removing TTL override rules: "
        iptables -t mangle -D POSTROUTING -o rmnet+ -j TTL --ttl-set ${TTLVALUE} &>/dev/null || true
        ip6tables -t mangle -D POSTROUTING -o rmnet+ -j HL --hl-set ${TTLVALUE} &>/dev/null || true
    else   
        echo "TTLVALUE set to 0, nothing to do..."
    fi
    echo "done"
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage ttl-override { start | stop | restart }" >&2
    exit 1
    ;;
esac

exit 0
