#!/bin/bash
RA="19:00:10"
DEC="70:39:51"
OBJ="GRW+708247"
EXPTIME=40000
FLATTIME=40000
OBS="Emelianov E.V."
BADWEATHER=1400
DATEEND=$(sunrise 12)

function sendcmd(){
    echo $1 | nc 192.168.70.33 10001 -q10
}

function point_tel(){
	touch lastpointing
	send_coords -r $1 -d $2
}

export http_proxy=""

# set lower limit to 5degr
send_command2mount ":So5#"

echo "Time diff: $(($DATEEND-$(date +%s)))"
if [ $(($DATEEND-$(date +%s))) -lt 3600 ]; then
	echo "There's less an hour for observation!"
	exit 2
fi

if [ $(($DATEEND-$(date +%s))) -gt 53200 ]; then
	echo "There's more than 12 hours till closing, check script data!"
	exit 3
fi

echo "GoTo object: ${RA} ${DEC}"
send_coords -r${RA} -d${DEC}
echo "Start taking object"

badweather=0
while true; do
	now=$(date +%s)
	ANS=$(curl localhost:55555/status 2>/dev/null)
	echo "Dome status: $ANS"
	if [ $ANS != "opened" ]; then
		echo "Closed"
		curl localhost:55555/weather 2>/dev/null > DomeClosed
		break;
	fi
	chkweather ${BADWEATHER} > lastweather && badweather=0 || badweather=$((badweather+1))
	[ $badweather -gt 5 ] && break
	[ -f stopobs ] && break
	[ -f exitjob ] && exit 0
	if [ "$now" -lt "$DATEEND" ]; then
		est=$(sendcmd ":Gmte#"|sed -e 's/^0*//' -e 's/#//')
		echo -e "\n\n\n\n\nEstimated time to flip: $est minutes"
		if [[ ("x$est" == "x") || ($est -lt 3) ]]; then
			point_tel "${RA}" "${DEC}"
			continue
		fi
		ST=$(send_coords | awk '{print $4}')
		[ "x$ST" == "x" ] && break
		if [ $ST -ne "0" ]; then
			point_tel "${RA}" "${DEC}"
			continue
		else
			preflash
			fli_control -r /tmp/10micron.fitsheader -x $EXPTIME -N "${OBS}" -O "${OBJ}" "$OBJ"
		fi
	else
		break
	fi
done

echo "Dome closed @ $(date)" >> closed
curl localhost:55555/close

relay_manage -s1
park_telescope

for x in $(seq 1 10); do
	preflash
	fli_control -r /tmp/10micron.fitsheader -x1 -O "bias" -d bias
	preflash
	fli_control -r /tmp/10micron.fitsheader -x $EXPTIME -O "dark" -d dark
#	preflash
#	fli_control -r /tmp/10micron.fitsheader -x $FLATTIME -O "dark" -d darkf
	preflash
	fli_control -r /tmp/10micron.fitsheader -n5 -x $FLATTIME -O "flat" flat
done

relay_manage -r1
echo "Closed @ $(date)" >> closed

STOPobs
