#!/bin/bash -e
### BEGIN INIT INFO
# Provides:          turnkey-init-fence
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Fences off appliance ports until after initialization
### END INIT INFO
#
# Author: Liraz Siri <liraz@turnkeylinux.org>
#
# how it works: iptables redirects http/https TCP connections to simplehttpd.py
#
#    redirect $HTTP_PORTS-> $HTTP_FENCE_PORT
#    redirect $HTTPS_PORTS -> $HTTPS_FENCE_PORT
#
#    configuration @ /etc/default/turnkey-init-fence
#
#        HTTP_FENCE_PORT=60080
#        HTTPS_FENCE_PORT=60443
#        HTTP_PORT=80
#        HTTPS_PORTS=443
#

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="Description of the service"
NAME=turnkey-init-fence
DAEMON=/usr/lib/inithooks/bin/simplehttpd.py
PIDFILE=/var/run/$NAME/simplehttpd.pid
SCRIPTNAME=/etc/init.d/$NAME

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Create pidfile directory
mkdir -p $(dirname $PIDFILE)

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
chown -R $RUNAS $(dirname $PIDFILE)

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

iptables_delete_redirect()
{
    dport=$1
    to_port=$2

    while true; do
        (2>&1 iptables -t nat -D PREROUTING -p tcp --dport $dport -j REDIRECT --to-port $to_port) > /dev/null || break
            
    done
}

iptables_add_redirect() 
{
    dport=$1
    to_port=$2

    iptables_delete_redirect $1 $2
    iptables -t nat -A PREROUTING -p tcp --dport $dport -j REDIRECT --to-port $to_port
}


iptables_redirect()
{
    case "$1" in
      start)
          op=iptables_add_redirect
        ;;
      stop)
          op=iptables_delete_redirect
        ;;
    esac

    for port in $HTTP_PORTS; do
        $op $port $HTTP_FENCE_PORT
    done

    for port in $HTTPS_PORTS; do
        $op $port $HTTPS_FENCE_PORT
    done
}

#
# Function that starts the daemon/service
#
do_start()
{
	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started
    start-stop-daemon --start --quiet --pidfile $PIDFILE --name $(basename $DAEMON) --startas $DAEMON --test > /dev/null \
		|| return 1
	start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON -- --runas=$RUNAS \
        --daemonize=$PIDFILE $WEBROOT $HTTP_FENCE_PORT $HTTPS_FENCE_PORT $HTTPS_FENCE_CERTFILE $HTTPS_FENCE_KEYFILE

	# Add code here, if necessary, that waits for the process to be ready
	# to handle requests from services started subsequently which depend
	# on this one.  As a last resort, sleep for some time.

    iptables_redirect start
}

#
# Function that stops the daemon/service
#
do_stop()
{
    iptables_redirect stop

	# Return
	#   0 if daemon has been stopped
	#   1 if daemon was already stopped
	#   2 if daemon could not be stopped
	#   other if a failure occurred
    start-stop-daemon --stop --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $(basename $DAEMON)
	RETVAL="$?"
	[ "$RETVAL" = 2 ] && return 2
	# Wait for children to finish too if this is a daemon that forks
	# and if the daemon is only ever run from this initscript.
	# If the above conditions are not satisfied then add some other code
	# that waits for the process to drop all resources that could be
	# needed by services started subsequently.  A last resort is to
	# sleep for some time.
    start-stop-daemon --stop --quiet --oknodo --retry=TERM/30/KILL/5 --user $RUNAS --name $(basename $DAEMON)

	[ "$?" = 2 ] && return 2
	# Many daemons don't delete their pidfiles when they exit.
	rm -f $PIDFILE

	return "$RETVAL"
}

case "$1" in
  start)
	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
	do_start
	case "$?" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	;;
  stop)
	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
	do_stop
	case "$?" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	;;
  status)
       status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
       ;;
  restart)
	#
	# If the "reload" option is implemented then remove the
	# 'force-reload' alias
	#
	log_daemon_msg "Restarting $DESC" "$NAME"
	do_stop
	case "$?" in
	  0|1)
		do_start
		case "$?" in
			0) log_end_msg 0 ;;
			1) log_end_msg 1 ;; # Old process is still running
			*) log_end_msg 1 ;; # Failed to start
		esac
		;;
	  *)
	  	# Failed to stop
		log_end_msg 1
		;;
	esac
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2
	exit 3
	;;
esac

:

