#!/bin/bash
#
# ===========================================================================
# Start and Stop Open connect via the command line as if it were a service
# 1 Nov 2016 Mike Gore
#
#Usage:
# uw start
#    - starts the VPN connection and prompts for a UWDIR userid and password
# uw stop
#    - closes the connection
# uw status
#    - Check the status of the openconnect process
# ===========================================================================

# We use the same structure as init functions
# Including the use of PID files
DAEMON=/usr/sbin/openconnect
PIDDIR=/var/run/openconnect
OCPID=$PIDDIR/openconnect.pid
export OCPID PIDDIR
# clear conflicting settings from the environment
unset TMPDIR

if [ ! -f $DAEMON ]
then
        echo "please install openconnect package"
        echo "    apt-get install openconnect"
        exit 1
fi

# make sure we have a directory with the pid in it
install -o root -g root -m 755 -d $PIDDIR
# ===========================================================================

case "$1" in
        start)
                if $DAEMON -b cn-vpn.uwaterloo.ca
                then

                        pidof $DAEMON >$OCPID
                        echo Started
                        exit 0
                else
                        rm -f $OCPID
                        echo Failed to start
                        exit 1
                fi
                ;;
        stop)
                if [ -f $OCPID ]
                then
                        kill $(cat $OCPID)
                        sleep 1
                else
                        exit 0
                fi
                if pidof $DAEMON >/dev/null
                then
                        echo process is running: $(cat $OCPID)
                        exit 1
                else
                        echo process has stopped
                        echo removing PID file
                        rm -f $OCPID
                        exit 1
                fi
                exit 0
                ;;
        restart)
                $0 stop
                sleep 1
                $0 start
                ;;
        status)
        if [ -f $OCPID ]
                then
                        if ps h $(cat $OCPID) >/dev/null
                        then
                                echo process is running: $(cat $OCPID)
                        else
                                echo process is dead with stale PID $(cat $OCPID)
                        fi
                fi
                exit $?
                ;;
        *)
                echo "Usage: /etc/init.d/smbd {start|stop|restart|status}"
                exit 1
                ;;
esac

exit 0