#! /bin/sh
#
# Author:	Andreas Olsson &lt;andreas@arrakis.se&gt;
# Version:	@(#)autossh_tunnel.foo  0.1  27-Aug-2008  andreas@arrakis.se
# Modified by RNC 14/10/9
#
# For each tunnel; make a uniquely named copy of this template.

## SETTINGS
#
# autossh monitoring port (needs to be unique on publichost)
MPORT=5124 ### amend as necessary
# the ssh tunnel to setup (also needs to be unique on publichost)
TUNNEL="-R 5024:localhost:22" ### amend the "5024" bit as necessary
# remote user
RUSER="myusername" ### amend as necessary
# remote server
RSERVER="publichost" ### amend as necessary
# keyfile
KEYFILE="/home/myusername/.../mykeyfile" ### amend to point to a real SSH private key (which will be accepted by publichost for this username)
# You must use the real autossh binary, not a wrapper.
DAEMON=/usr/lib/autossh/autossh
#
## END SETTINGS

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

NAME=`basename $0`
PIDFILE=/var/run/${NAME}.pid
SCRIPTNAME=/etc/init.d/${NAME}
DESC="the tunnel"

test -x $DAEMON || exit 0

#RNC# export AUTOSSH_PORT=${MPORT}
export AUTOSSH_PIDFILE=${PIDFILE}
#RNC# ASOPT=${TUNNEL}" -f -N "${RUSER}"@"${RSERVER}
ASOPT="-M "${MPORT}" -N -f -i "${KEYFILE}" "${TUNNEL}" "${RUSER}"@"${RSERVER}

#	Function that starts the daemon/service.
d_start() {
	start-stop-daemon --start --quiet --pidfile $PIDFILE \
		--exec $DAEMON -- $ASOPT
	if [ $? -gt 0 ]; then
	    echo -n " not started (or already running)"
	else
	    sleep 1
	    start-stop-daemon --stop --quiet --pidfile $PIDFILE \
		--test --exec $DAEMON > /dev/null || echo -n " not started"
	fi
}

#	Function that stops the daemon/service.
d_stop() {
	start-stop-daemon --stop --quiet --pidfile $PIDFILE \
		--exec $DAEMON \
		|| echo -n " not running"
}

case "$1" in
  start)
	echo -n "Starting $DESC: $NAME"
	d_start
	echo "."
	;;
  stop)
	echo -n "Stopping $DESC: $NAME"
	d_stop
	echo "."
	;;
  restart)
	echo -n "Restarting $DESC: $NAME"
	d_stop
	sleep 1
	d_start
	echo "."
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
	exit 3
	;;
esac

exit 0
