Auto update iptables DDWRT

custom script:

wan=`nvram get wan_ipaddr`
last=`cat /tmp/last_wan_ipaddr`
echo "WAN IP: $wan" > /tmp/ipv6forward.log
echo "Last WAN IP: $last" >> /tmp/ipv6forward.log
# Check if IP is updated
if [ "$wan" != "$last" ]; then
  echo "New WAN IP detected." >> /tmp/ipv6forward.log
  # If this is the first time script is adding rules, add a FILTER rule that accept the DNAT FORWARD rule
  if [ -f /tmp/last_wan_ipaddr ]; then
    # Not first time, delete old DNAT
    iptables -t nat -D PREROUTING -j DNAT -d $last -p 41 --to-destination 10.10.10.7 >> /tmp/ipv6forward.log    
  else
    # First time, wait for router to settle (ddwrt will clear iptables on startup)
    sleep 30
    # Remove DROP policy
    iptables -t filter -D FORWARD -j DROP >> /tmp/ipv6forward.log
    # Add DNAT rule
    iptables -t filter -A FORWARD -j ACCEPT -p 41 -d 10.10.10.7 >> /tmp/ipv6forward.log
    # Add DROP polocy (last place)
    iptables -t filter -A FORWARD -j DROP >> /tmp/ipv6forward.log
  fi
  iptables -t nat -A PREROUTING -j DNAT -p 41 -d $wan --to-destination 10.10.10.7 >> /tmp/ipv6forward.log
  # write wan_ipaddr to tmp
  echo $wan > /tmp/last_wan_ipaddr
fi

startup script:

nvram get rc_custom > /tmp/custom.sh
chmod +x /tmp/custom.sh

cron:

* * * * * root /tmp/custom.sh