#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          cntlm
# Required-Start:    $remote_fs $syslog $time $network
# Required-Stop:     $remote_fs $syslog $time $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Authenticating HTTP accelerator for NTLM secured proxies
# Description:       Cntlm is meant to be given your proxy address and becomming
#                    the primary proxy then, listening on a selected local port. 
#                    You point all your proxy-aware programs to it and don't ever
#                    have to deal with proxy authentication again.
### END INIT INFO
#
# DAEMON             Location of the binary
# PIDFILE            Make sure that you or, if used, -U uid can create/write it
# TIMEOUT            How long to wait for active connections to finish before 
#                    forcing cntlm to stop with a second signal 
# RUNAS              Name or number of the non-privileged account to run as
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/cntlm
NAME=cntlm
DESC="CNTLM Authentication Proxy"

# Set default values
PIDFILE=/var/run/cntlm/cntlm.pid
TIMEOUT=1
RUNAS=cntlm

test -x $DAEMON || exit 0

. /lib/lsb/init-functions
test -r /etc/default/rcS && . /etc/default/rcS

# Include custom values if available
if [ -f /etc/default/cntlm ] ; then
	. /etc/default/cntlm
fi

DAEMON_OPTS="$DAEMON_OPTS -U $RUNAS -P $PIDFILE"
PIDDIR=`dirname $PIDFILE 2>/dev/null`

start() {
	log_daemon_msg "Starting $DESC" "$NAME"

	if [ -n "$PIDDIR" -a ! -d "$PIDDIR" ]; then
		mkdir -p "$PIDDIR" 2>/dev/null
		chown "$RUNAS" "$PIDDIR" 2>/dev/null
		chmod 755 "$PIDDIR" 2>/dev/null
	fi

	start-stop-daemon --oknodo --quiet --start --pidfile $PIDFILE --name $NAME --startas $DAEMON -- $DAEMON_OPTS 2>/dev/null

	log_end_msg $?
}

stop() {
	log_daemon_msg "Stopping $DESC" "$NAME"
	start-stop-daemon --oknodo --quiet --stop --retry -HUP/$TIMEOUT/-HUP/2/forever/-KILL --pidfile $PIDFILE --name $NAME

	log_end_msg $?
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart|reload|force-reload)
		stop
		start
		;;
	status)
	  status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $?
	  ;;
	*)
		echo "Usage: $0 {start|stop|restart|reload|force-reload|status}" >&2
		exit 2
		;;
esac

exit 0
