#!/bin/sh

. /usr/html/axis-cgi/lib/functions.sh

trap 'rm -rf $tmpdir' EXIT
PRG=$(__whoami)

croak() {
	logger -t$PRG -pcrit "$*"
	__cgi_errhd 500 "Error while compiling Server Report: $*!"
	exit 1
}

generate_report() {

	[ $# -gt 0 ] && [ "$1" ] ||
		croak "Bad destination file '$1' argument!"

	/usr/sbin/gen_serverreport.sh >$1
}

construct_and_send_zip() {
	local p mac zipname

	[ $# -gt 1 ] && [ "$1" ] && [ -d "$1" ] ||
		croak "Bad directory '$1' argument!"

	p=Properties.System.SerialNumber
	mac=$(parhandclient --nocgi get $p - RAW) ||
		croak "Failed to get parameter $p!"

	zipname=Axis_SR_$(date '+%Y%m%d_%H%M%S')_$mac.zip

	cd $1
	shift

	zip -jq $zipname $* || croak "Failed to perform zip operation!"

	printf "Content-Type: application/zip\r
Content-Disposition: attachment; filename=%s\r
Expires: Thu, 01 Dec 1994 16:00:00 GMT\r\n\r\n" $zipname

	cat $zipname
}

generate_radar_files() {
	[ $# -eq 3 ] || croak "Bad number of arguments!"
	[ "$1" ] && [ "$2" ] && [ "$3" ] || croak "Bad arguments: blank!"

	local result= f dest

	for f in /tmp/radar-diagnostics/*; do
		[ -f $f ] || continue
		dest=$1/${f##*/}
		cp $f $dest || {
			echo "$PRG: Error copying radar diagnostic file $f!" >>$2
			continue
		}
		result="${result:+$result
}$dest"
	done

	eval $3=\$result
}

generate_files() {
	[ $# -eq 2 ] || croak "Bad number of arguments!"

	[ "$1" ] && [ "$2" ] || croak "Bad destination file argument(s)!"

	generate_report $1
	local dadlog=/usr/local/packages/dad/localdata/log.db
	[ -r $dadlog ] || dadlog=

	eval $2=\$dadlog
}

if [ $# -gt 0 ] && [ "$1" ]; then
	mode=$1
else
	mode=$(__qs_getparam mode) || :
fi

tmpcgidir=/var/cache/httpd/cgi
[ -d $tmpcgidir ] || mkdir -p $tmpcgidir || croak "Error creating '$tmpcgidir'!"

name=${PRG%.cgi}

tmpdir=$(mktemp -d "$tmpcgidir/${name}XXXXXX") ||
	croak "Error creating temporary directory!"

tmpfile=$tmpdir/${name}_cgi.txt
tmpimage=$tmpdir/${name}_image.jpg

case $mode in
	zip)
		generate_files $tmpfile tmpdadlog
		construct_and_send_zip $tmpdir $tmpfile $tmpdadlog
		;
	zip_with_image)
		generate_files $tmpfile tmpdadlog
		/usr/sbin/jpeg_snapshot $tmpimage || {
			echo "$PRG: Error generating snapshot image for server report." >>$tmpfile
			tmpimage=
		}
		generate_radar_files $tmpdir $tmpfile radarfiles
		construct_and_send_zip $tmpdir $tmpfile $tmpimage $tmpdadlog $radarfiles
		;
	text|'')
		__cgi_hdgen yes text/plain
		generate_report $tmpfile
		cat $tmpfile
		;
	*)
		croak "Invalid mode '$mode'!"
		;
esac