#!/bin/bash

# --------------------------------
# copyleft Axel Amthor, 10/2007
# --------------------------------

# Config
HOST=localhost
PORT=8080
USER=admin
PASSWD=admin
CAMSPECIFIER="cam"
LWP="lwp-request"

OPTIONS="vc:H:p:a:hU:P:r:"
ME=`basename $0`
REQUESTPARMS="-s"
USAGE="$ME [-h] [-v] [-r <credentials file>] [-H <hostname>] [-p <portnum>] [-U <username] [-P <passwd>] [{-c <cam> -a <action>} ...]"
VERBOSE=false


# Vars
CAMLIST=""
CMDLIST=""
PARAMLIST=""

function mcontrol () {
	lcmd="$2"
	lcam="$1"
	l=0
	start=false
	${LWP} $REQUESTPARMS http://${USER}:${PASSWD}@${HOST}:$PORT/${lcam}/${lcmd}>/tmp/$$ </dev/null
	while read line 
	do
		if [ $start == true ]
		then
			ianswer="`echo $line|sed 's#<[^>]*>##g'`"
			break;
		fi
		if [ $l -eq 0 ]
		then
			set $line
			status="$1"
		fi
		start=false
		if [ "$line" == "<body>" ]
		then
			start=true
		fi
		let l++
	done < /tmp/$$
	rm /tmp/$$

	debug http status is \'"$status"\'
	debug answer body is \'"$ianswer"\'
	e=-1
	if [ $status == 200 ]
	then
		e=0
	fi
	return $e
}

function debug () {
	test $VERBOSE = true && echo $@ >&2
}

#some checks
if type ${LWP} >/dev/null 2>&1
then
	:
else
	echo "${LWP} could not be found or is not installed, please check" >&2
	exit -1
fi

while getopts $OPTIONS option $*
do
	case "$option" in
	h)	cat <<-__SHORTHELP__
$ME: control motion by batch and cron

Synopsis: $USAGE

-h gives this output.

Instead of passing username and password on the command line, it is possible to put them in to a file and pass
this file with parameter -r to $ME. The file must consist of one line containing the username and the password,
delimited by space and termitated by cr/nl.

$ME takes following parameters:
optional parameters:
        hostname:	host to connect to (localhost)
        portnum:	port to connect to (8080)
        username:	username to log in (admin)
        passwd:     password to log in (admin)
All optional parameters must be set before any camera action parameters on the command line.
mandatory parameters:
        cam:     cam to control, refers to the thread # in motion (cam # 0 menas all cameras!)
        action:  action to be passed to the motion thread controling this cam.
                 Actually, this is the path part of the motion html control interface, but some handy
                 abbreviations exist, see below.

Actions:
        long name            short name
        detection/start      dstart
        detection/pause      dpause
        detection/status     dstatus
        detection/connection dcon
        (all "action" part of the html control interface, it's obviously the path part of the URL)

Actions can be repeated on the command line. For instance:
        $ME -c 0 -a dpause -c 1 -a dstart
turns off detection on cam 0 and turns on detection on cam 1.
Multiple action parts always refer to the last left camera. For instance
        $ME -c 0 -a dpause -a detection/status
would first turn off detection on cam 0 and then retrieve the current detection status of the same camera.

This script requires perl LWP packages to be properly installed.
__SHORTHELP__
        ;;

	H) HOST="$OPTARG";;
	p) PORT="$OPTARG";;
	U) USERNAME="$OPTARG";;
	P) PASSWD="$OPTARG";;
	v) VERBOSE=true;;
	
	c) cam="$OPTARG";;
	a) action="$OPTARG";;

	r) 	if [ -f "$OPTARG" ]
        then
        	while read user pass
        	do
                USER=$user
                PASSWD=$pass
        	done <"$OPTARG"
        else
        	echo can not open \'$OPTARG\' >&2
        	exit -1
        fi;;

	*) echo $USAGE;;
	esac

	laction="$action"
	case "$action" in
        dstart) laction=detection/start;;
        dpause) laction=detection/pause;;
        dstatus) laction=detection/status;;
        dcon)	 laction=detection/connection;;
	esac
	
	if [ "x$cam" != x -a "x$laction" != x ]
	then
        debug setting action $action on cam $cam
        mcontrol $cam "$laction"
        echo $ianswer
	fi
	
	action=""

done

