#!/bin/sh 
#
# Script used to start and stop the nzbget usenet service
#
# Copyright (C) 2009 orbisvicis <orbisvicis@users.sourceforge.net>
# Copyright (C) 2009 Andrei Prygounkov <hugbug@users.sourceforge.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#

# Location of the nzbget executable
export NZBGET_BINARY="/usr/local/bin/nzbget"

# -----------------------------------------------------------------
# start/stop section

execCommand() {
    "$NZBGET_BINARY" $@
	sleep 1 # allows prompt to return
}

start() {
	execCommand "--daemon"
}

stop() {
	execCommand "--quit"
}

status() {
    execCommand "--log 5"
}


case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		sleep 10 # since stop is backgrounded
		start
		;;
	pstatus) 
		retval=$(pgrep -l -f "$NZBGET_BINARY --daemon"  > /dev/null ; echo $?)
		if [ "$retval" = "0" ] ; then 
			echo "        ------- nzbget *is* running -------"
			ps -Ho user,pid,cmd:32,pcpu -C nzbget
			exit 0
		else 
			echo "        ------- nzbget is *not* running -------"
			exit 0
		fi
		;;
	istatus)
		status
		;;
	*)
		echo "Usage $0 {start|stop|restart|pstatus|istatus}"
		exit 1
esac

exit 0
