#!/bin/sh /etc/rc.common
# Copyright (C) 2007 OpenWrt.org

START=90
INTERFACE=br-lan
PORT=1337

# check if configuration exists
[ -e "/etc/redsocks.conf" ] || exit 0

iptable_start() {
    /bin/echo -n "running proxy bypass iptables ..."

    # Run iptable commands
    iptables -t nat -N REDSOCKS

    iptables -t nat -A REDSOCKS -d 0.0.0.0/8 -j RETURN
    iptables -t nat -A REDSOCKS -d 10.0.0.0/8 -j RETURN
    iptables -t nat -A REDSOCKS -d 127.0.0.0/8 -j RETURN
    iptables -t nat -A REDSOCKS -d 169.254.0.0/16 -j RETURN
#    iptables -t nat -A REDSOCKS -d 172.16.0.0/12 -j RETURN
    iptables -t nat -A REDSOCKS -d 192.168.0.0/16 -j RETURN
    iptables -t nat -A REDSOCKS -d 224.0.0.0/4 -j RETURN
    iptables -t nat -A REDSOCKS -d 240.0.0.0/4 -j RETURN

    iptables -t nat -A REDSOCKS -p tcp -j REDIRECT --to-ports ${PORT}

    iptables -t nat -A PREROUTING -i ${INTERFACE} -p tcp -j REDSOCKS

    iptables -A INPUT -i br-lan -p tcp --dport ${PORT} -j ACCEPT

    /bin/echo " done"
}

iptable_stop() {
    /bin/echo -n "cleaning proxy bypass iptables ..."

    # Run iptable commands
    iptables -t nat -F REDSOCKS
    iptables -t nat -F PREROUTING
    iptables -t nat -F POSTROUTING
    iptables -F INPUT
    iptables -F FORWARD
    iptables -t nat -X REDSOCKS

    /bin/echo " done"
}

start() {
    if [ -e "/var/run/redsocks.pid" ]; then
        echo "proxy bypass is already running"
        exit 0
    fi

    /bin/echo -n "running proxy bypass ..."

    # startup the safety-wrapper for the daemon
    /usr/sbin/redsocks -c /etc/redsocks.conf -p /var/run/redsocks.pid

    /bin/echo " done"
    iptable_start
}


stop() {
    if [ ! -e "/var/run/redsocks.pid" ]; then
        echo "proxy bypass is not running"
        exit 0
    fi

    /bin/echo -n "stopping proxy bypass ..."

    # kill the process
    /bin/kill $(cat /var/run/redsocks.pid)
    rm /var/run/redsocks.pid

    echo " done"
    iptable_stop

    /bin/echo -n "restarting firewall ..."
    /etc/init.d/firewall restart &> /dev/null
    /bin/echo " done"
}