#!/bin/sh -e

. /lib/rcscripts/sh/error.sh
. /lib/rcscripts/sh/string.sh

MO_DF_TMP=/var/run/ptz/mo_data_file_tmp
MO_DF=/var/run/ptz/mo_data_file

HWID=
PTZCAL_MECH_OFFSET=
PTZCAL_OPT_OFFSET=

invert_optical_offset_values() {
	local f=invert_optical_offset_values IFS=';'

	[ $# -eq 2 ] && [ "$1" ] ||
		error "$f: wrong number of arguments!"

	validate_varname $1 ||
		error "$f: invalid variable '$1' value"

	[ $HWID = 1ED.1 ] || [ $HWID = 1ED.2 ] ||
	[ $HWID = 1EE.1 ] || [ $HWID = 1EE.2 ] ||
	[ $HWID = 1C0.2 ] || [ $HWID = 1C0.3 ] || {
		eval $1=\$2
		return 0
	}

	[ "$2" ] || {
		warning "$f: Invalid bootblock parameter, offsets will not be correct"
		eval $1=\$2
		return 0
	}

	local i inverted_value= num grp grp1

	for grp in $2; do
		IFS=,
		i=1
		grp1=
		for num in $grp; do
			[ $i -eq 1 ] || num=$((0 - $num))
			grp1=${grp1:+$grp1,}$num
			i=$(($i + 1))
		done
		inverted_value=${inverted_value:+$inverted_value;}$grp1
	done
	eval $1=\$inverted_value
}

HWID=$(bootblocktool -err -x HWID 2>/dev/null) ||
	error "Failed to read HWID from bootblock parameters"

PTZCAL_MECH_OFFSET=$(bootblocktool -x PTZCAL_MECH_OFFSET 2>/dev/null || :)
PTZCAL_OPT_OFFSET=$(bootblocktool -x PTZCAL_OPT_OFFSET 2>/dev/null || :)
invert_optical_offset_values PTZCAL_OPT_OFFSET "$PTZCAL_OPT_OFFSET"

if [ "$PTZCAL_MECH_OFFSET" ] || [ "$PTZCAL_OPT_OFFSET" ]; then
	>$MO_DF_TMP || error "Could not create file $MO_DF_TMP"
	chmod o-wx,a+r $MO_DF_TMP || {
		set_error_msg
		log_error "Failed to change attributes of $MO_DF_TMP"
	}
	prs=36000
	trs=36000
	steps_conf=/usr/share/ptz/ptzmath_pt_mech.conf
	[ ! -r $steps_conf ] || {
		prs=$(sed -rn 's/^PanRotationSteps[[:blank:]]*=[[:blank:]]*([0-9]+)/\1/p' $steps_conf)
		trs=$(sed -rn 's/^TiltRotationSteps[[:blank:]]*=[[:blank:]]*([0-9]+)/\1/p' $steps_conf)
	}
	printf "PAN_ROTATION_STEPS=%s
TILT_ROTATION_STEPS=%s
PTZCAL_MECH_OFFSET=%s
PTZCAL_OPT_OFFSET=%s
" "$prs" "$trs" "$PTZCAL_MECH_OFFSET" "$PTZCAL_OPT_OFFSET" >$MO_DF_TMP 2>/dev/null ||
		error "Error encountered creating content of $MO_DF_TMP"

	mv $MO_DF_TMP $MO_DF || error "Could not create file $MO_DF"
fi