#! /bin/sh
### BEGIN INIT INFO
# Provides:          wpnetlink
# Required-Start:    $local_fs $network $remote_fs $time
# Required-Stop:     $local_fs $network $remote_fs $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Comb MKII Plus/Lite firmware manager
# Description:       Comb MKII Plus/Lite firmware manager
### END INIT INFO
#
# Author:       Ryan Murray <rmurray@debian.org>
#

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/opt/comb/bin

DAEMON=/opt/comb/bin/wpnetlink
PIDFILE=/run/lock/wpnetlink

#Read config file in ~root
if [ -e /root/.config_comb ];then
	. /root/.config_comb
    elif [ -e /home/root/.config_comb ];then
	. /home/root/.config_comb
fi;

if [ "${PRINTER}" ];then
	export PRINTER
fi;

test -x $DAEMON || exit 0

if [ -e /lib/lsb/init-functions ];then
	. /lib/lsb/init-functions
    elif [ -e /etc/init.d/functions ];then
	. /etc/init.d/functions
fi

case "$1" in
  start)
	if [ -e /lib/lsb/init-functions ];then
		log_daemon_msg "Starting deferred execution scheduler" "wpnetlink"
		start_daemon -p $PIDFILE $DAEMON
		log_end_msg $?
		echo 1 > /proc/sys/net/ipv4/ip_forward
	    elif [ -e /etc/init.d/functions ];then
		echo -n "Starting wpnetlink: "
		start-stop-daemon --start -p $PIDFILE $DAEMON && echo "OK"
	fi;
	if ! iptables -t nat -vnL WPNETLINK_POST >/dev/null 2>&1;then
		iptables -t nat -N WPNETLINK_POST
		iptables -t nat -I POSTROUTING -j WPNETLINK_POST
	else
		iptables -t nat -F WPNETLINK_POST
	fi;
	if ! iptables -t nat -vnL WPNETLINK_PRE >/dev/null 2>&1;then
		iptables -t nat -N WPNETLINK_PRE
		iptables -t nat -I PREROUTING -j WPNETLINK_PRE
	else
		iptables -t nat -F WPNETLINK_PRE
	fi;
	iptables -t nat -I WPNETLINK_POST -j MASQUERADE -s 192.168.2.2/24
	iptables -t nat -I WPNETLINK_POST -j MASQUERADE -s 192.168.100.2/30
	iptables -t nat -I WPNETLINK_POST -j MASQUERADE -s 172.31.255.192/30
	iptables -t nat -I WPNETLINK_PRE -p tcp --dport 4444 -j DNAT --to 192.168.2.2:22

	#Setup ESP GPIO
	flash_switch.sh --log
	;;
  stop)
	if [ -e /lib/lsb/init-functions ];then
		log_daemon_msg "Stopping deferred execution scheduler" "wpnetlink"
		[ -e ${PIDFILE} ] && kill -9 `cat ${PIDFILE}`
		log_end_msg $?
		echo 0 > /proc/sys/net/ipv4/ip_forward
	    elif [ -e /etc/init.d/functions ];then
		echo -n "Stopping wpnetlink: "
		start-stop-daemon --stop -p $PIDFILE $DAEMON
	fi;
	if [ -e ${PIDFILE} ];then
		rm ${PIDFILE}
		iptables -t nat -F WPNETLINK_POST
		iptables -t nat -F WPNETLINK_PRE
	fi;
	;;
  force-reload|restart)
	$0 stop
	$0 start
	;;
  status)
	if [ -e /lib/lsb/init-functions ];then
		status_of_proc -p $PIDFILE $DAEMON wpnetlink && exit 0 || exit $?
	    elif [ -e /etc/init.d/functions ];then
		status wpnetlink && exit 0 || exit $?
	fi;
	;;
  *)
    echo "Usage: /etc/init.d/wpnetlink {start|stop|restart|force-reload|status}"
    exit 1
    ;;
esac

exit 0
