#!/bin/sh
# wxbatch
# Copyright (c) 2001-2013 Central North Publishing Limited.
# All rights reserved.
# $Id: wxbatch,v 1.1 2009/05/07 03:33:32 craig Exp $

IFS=" "
PATH=$PATH:/bin:/usr/bin:/usr/local/bin
export IFS PATH

if [ -f /etc/sysconfig/clock ]; then
	. /etc/sysconfig/clock
fi

version="2.11.2 beta"
copyright="Copyright (c) 2001-2013 Central North Publishing Limited.
All rights reserved."

prog=`basename $0`
tmp=/tmp/$prog.$$

wxopts="-q"
wxmapopts="-q"
recopts=""
noaaenh="norm histeq hvc msa mcir no"
ext="jpg"
dir=""
raw=
map=
minlength=0
flipMeteor=1
preserveraw=
noaaSats=
otherSats=
runprog=

usage()
{
	cat <<-%%% >&2
	Usage: $prog [-e "<enh>"] [-C|-W] [-D <dir>] [-i <ext>] [-8|-16] [-c] [-r] [-m] [-k <text>] [-H <cont>] [-l <lev>] [-t <sec>] [-f <hz>] [-s <device>] [-R <name>] [-P <dev>] [-E <min>] [-L <lat/lon/alt>] [-n <city>] [-T <sat> [...]] [-M <elev>] [-A <elev>] [-Q{0|1}] [-X "<prog>"] [-IFoVh]
	  where: -e <enh>   list of enhancements for NOAA (default "$noaaenh")
	         -C         look for 2400Hz carrier instead of sound level increase
	         -W         start/stop recording on WEFAX start/stop signals
	         -D <dir>   directory to place audio recordings and generated images
	         -i <ext>   image file type extension (default $ext)
	         -8         record 8 bit audio samples
	         -16        record 16 bit audio samples (default)
	         -c         crop telemetry lines out of images
	         -r         generate raw PNG images only
	         -m         generate and use overlay map
	         -k <text>  overlay text onto image
	         -H <cont>  select contrast (histeq, linear, none, default histeq)
	         -l <lev>   sound trigger level (0 - 100, default 25)
	         -t <sec>   finish recording delay (default 60)
	         -f <hz>    sample rate (default 11025)
	         -s <dev>   soundcard device (default "/dev/dsp")
	         -R <name>  receiver control mode
	         -P <dev>   receiver control port
	         -E <min>   eliminate recordings less than min minutes in length
	         -L <l/l/a> set location (lat/lon/alt meters)
	         -n <city>  set location by "city, country" name
	         -T <sat>   record only satelite sat (multiple options may be used)
	         -M <elev>  record only if max. elevation is above (default 5.0)
	         -A <elev>  record only while satellite is above (default 1.0)
	         -Q {0|1}   disable (0) or enable (1) squelch (default enable)
	         -X <prog>  execute program on completion of image processing
	         -I         interpolate and oversample (50% larger images)
	         -F         flip Meteor 3-5 images
	         -o         overwrite output file if it exists
	         -V         print program version and exit
	         -h         display usage
	wxbatch version $version
	$copyright
	%%%
	exit 1
}

build_image()
{
	file=$1
	type=$2
	lctype=`echo "$type" | tr '[A-Z ]' '[a-z_]'`
	base=`echo "${file}" | sed 's/\.[^.]*$//'`
	lcbase="$lctype-$base"

	lhr=`date +%H`
	if [ ${lhr:=0} -le 16 ]; then
		if [ "$type" == "Meteor3" -a "$flipMeteor" == 1 ]; then
			direc=-N
		else
			direc=-S
		fi
	else
		if [ "$type" == "Meteor3" -a "$flipMeteor" == 1 ]; then
			direc=-S
		else
			direc=-N
		fi
	fi

	case "$type" in
	NOAA*|noaa*)
		case "$type" in
		NOAA*1*|noaa*1*)
			if [ -n "$map" ]; then
				if [ ! -s ${base}.map ]; then
					eval wxmap ${wxmapopts} -b 0 -T ${type} -300 ${base}.map
				fi
				mapopts="-m${base}.map"
			else
				mapopts=
			fi
			;;
		*)
			if [ -n "$map" ]; then
				if [ ! -s ${base}.map ]; then
					if [ "$noaaSats" == "" ]; then
						noaaSats="-T 'NOAA 12' -T 'NOAA 15' -T 'NOAA 17'"
					fi
					eval wxmap ${wxmapopts} -b 0 ${noaaSats} -300 ${base}.map
				fi
				mapopts="-m${base}.map"
			else
				mapopts=
			fi
			;;
		esac
		if [ -n "$raw" ]; then
			wxtoimg $wxopts -t "$type" -16r ${file} "${lcbase}.png"
		else
			# create a whole series of images
			wxtoimg $wxopts -t "$type" -16r ${file} ${lcbase}-raw.png
			if [ -s ${lcbase}-raw.png ]; then
				for e in $noaaenh
				do
					case "$e" in
					norm|normal|none)
						wxtoimg $mapopts $wxopts $direc ${lcbase}-raw.png "${lcbase}.${ext}"
						;;
					raw)
						wxtoimg $wxopts -16r $direc ${lcbase}-raw.png "${lcbase}-%e.png"
						;;
					pristine|pris)
						wxtoimg $mapopts $wxopts -p $direc ${lcbase}-raw.png "${lcbase}-%e.${ext}"
						;;
					histeq)
						for chan in a b; do
							wxtoimg $mapopts $wxopts $direc -${chan} -e $e ${lcbase}-raw.png "${lcbase}-histeq${chan}.${ext}"
						done
						
						;;
					*)
						wxtoimg $mapopts $wxopts $direc -e $e ${lcbase}-raw.png "${lcbase}-%e.${ext}"
						;;
					esac
				done
			fi
			if [ ! -n "$preserveraw" ]; then
				rm -f ${lcbase}-raw.png
			fi
		fi
		;;
	*)
		satopt=
		if [ -n "$map" ]; then
			case "$type" in
			Meteor3)
				satopt="-T 'METEOR 3-5'"
				;;
			Meteor2)
				satopt="-T 'METEOR 2-21'"
				;;
			Resurs)
				satopt="-T 'Resurs O1-N4'"
				;;
			esac
		fi
		if [ -n "$satopt" ]; then
			if [ ! -s ${base}.map ]; then
				eval wxmap ${wxmapopts} -b 0 "$satopt" -300 ${base}.map
			fi
			mapopts="-m${base}.map"
		else
			mapopts=
		fi
		if [ -n "$raw" ]; then
			wxtoimg $wxopts -t "$type" -16r ${file} "${lcbase}.png"
		else
			wxtoimg $wxopts -t "$type" -16r ${file} "${lcbase}-raw.png"
			wxtoimg $mapopts $wxopts $direc ${lcbase}-raw.png "${lcbase}.${ext}"
			if [ ! -n "$preserveraw" ]; then
				rm -f ${lcbase}-raw.png
			fi
		fi
		;;
	esac
	if [ -n "$runprog" ]; then
		exec $runprog "${file}"
	fi
	return 0
}

main()
{
	while getopts "816CWcrmk:H:e:D:i:l:t:f:s:R:P:E:L:n:T:M:A:Q:X:IFoVh" arg
	do
		case "$arg" in
		8|1|6)
		   recopts="$recopts -${arg}"
		   ;;
		C|W)
		   recopts="$recopts -${arg}"
		   ;;
		c) wxopts="$wxopts -${arg}"
		   ;;
		r) ext=png
		   raw=yes
		   ;;
		m) map=yes
		   ;;
		k|H)
		   wxopts="$wxopts -${arg} '$OPTARG'"
		   ;;
		e) noaaenh=$OPTARG
		   ;;
		D) dir=$OPTARG
		   ;;
		i) ext=$OPTARG
		   ;;
		l|t|f|s|R|P|Q|A)
		   recopts="$recopts -${arg} $OPTARG"
		   ;;
		E) minlength=$OPTARG
		   ;;
		L|n|M)
		   recopts="$recopts -${arg} '$OPTARG'"
		   wxmapopts="$wxmapopts -${arg} '$OPTARG'"
		   ;;
		T) recopts="$recopts -${arg} '$OPTARG'"
                   case "$OPTARG" in
		   Noaa*|NOAA*|noaa*)
			noaaSats="$noaaSats -${arg} '$OPTARG'"
			;;
		   *)
			otherSats="$otherSats -${arg} '$OPTARG'"
			;;
		   esac
		   ;;
		X) runprog=$OPTARG
		   ;;
		I) wxopts="$wxopts -${arg}"
		   ;;
		F) case "$flipMeteor" in
		   0) flipMeteor=1;;
		   *) flipMeteor=0;;
		   esac
		   ;;
		o) recopts="$recopts -${arg}"
	           wxopts="$wxopts -${arg}"
	           wxmapopts="$wxmapopts -${arg}"
		   ;;
		V) echo "wxbatch version $version"
		   echo "$copyright"
		   exit 0
		   ;;
		h) usage
		   ;;
		*) usage
		   ;;
		esac
	done
	na=`expr $OPTIND - 1`
	shift ${na:=0}
	case "$#" in
	0) ;;
	*) usage ;;
	esac

	if wxtoimg -Y; then
		:
	else
		exit 101
	fi
	if [ -n "$dir" ]; then
		if cd $dir; then
			:
		else
			echo "$prog: error: can not change to directory '$dir'." >&2
			exit 2
		fi
	fi

	rm -f $tmp
	trap "rm -f $tmp; exit 9" 1 2 3 15
	while :
	do
		eval wxrec -x $recopts 2>&1 | tee $tmp
		file=`awk '/^Output File:/ { print $3 }' $tmp`
		if [ -z "$file" ]; then
			continue
		fi
		if [ ! -s "$file" ]; then
			continue
		fi
		length=`awk -F'[: ]' '/^Record Duration/ { print $4 }' $tmp`
		type=`awk '/^Satellite:/ { print $2, $3 }' $tmp`
		rm -f $tmp

		if [ ${minlength:=0} -gt 0 -a ${length:=9999} -lt ${minlength:=0} ]; then
			echo "Status: eliminating $length minute recording $file..." >&2
			rm -f $file
		else
			if [ -z "$type" ]; then
				type=`wxtoimg -F ${file} 2>&1 | awk '/^Satellite:/ { print $2 }'`
			fi
			echo "Status: processing $type recording $file in background..." >&2
			build_image "$file" "$type" &
		fi
	done
}

main "$@"
