#!/bin/bash

SQL="/home/prokop/scripts/parse_handylog.sh"

DATA_TMP="/tmp/delo4/rdh"

DATA_DIR_IN="/mnt/raid/delos/delo4/hs"
#DATA_DIR_OUT="/mnt/jaruska/blesky/delo/handy"
DATA_DIR_OUT="/mnt/raid/storage/lsbb/handy"

RDH="/home/prokop/scripts/pustrdh4.pro"
IDL_TEMP="/home/prokop/idl_temp"

HTML_DIR="/var/www/html/lsbb"
HTML_PICS="/var/www/html/lsbb/pics_d/"

#

if [ -d "$DATA_TMP" ]
then
        rm -rf $DATA_TMP/*
else
        mkdir -p $DATA_TMP
fi

INPUT=""
while [ "$INPUT" != "q" ]
do
	cd $DATA_TMP
	#FNAME=$(ls -tr1 $DATA_DIR_IN | head -1)
	FNAME=$(ls -1 $DATA_DIR_IN | head -1)

	if [ -z $FNAME ]
	then
		sleep 2
		echo -n "."
		continue
	fi

	if [ -e $DATA_DIR_IN/$FNAME ]
	then
		#DIRNAME=${FNAME%.tar.bz2}
		DIRNAME=${FNAME%.7z}
		mkdir $DATA_TMP/$DIRNAME
		cd $DATA_TMP/$DIRNAME
		#cd $DATA_DIR_IN/$FNAME
		#tar xjf $DATA_DIR_IN/$FNAME
		7za e $DATA_DIR_IN/$FNAME

		BIN_NAME=$(ls *.bin)
		BNAME=${BIN_NAME%.bin}

		echo $BNAME

		# check GPS trigger
		GPS_TRIG=$(grep "Trigger at:" $BNAME.txt | cut -d" " -f3)
		if [[ $GPS_TRIG = *. ]]
		then
			USB_TRIG=$(grep "USB trig at:" *.txt | cut -d" " -f 4)
			sed -i 's/Trigger at:.*/Trigger at: '$USB_TRIG'/g' $BNAME.txt
			echo "Only USB trigger time!" >> $BNAME.txt
		fi
		#for i in {0,3,1,2}
		#do
		#	dd if=$BIN_NAME ibs=67107840 count=1 skip=$i 2>/dev/null | cat >> ${BNAME}_tmp.bin
		#done
		#mv ${BNAME}_tmp.bin ${BNAME}.bin

		touch overview.txt
		cp $IDL_TEMP/overview{0..3}.idl .
		idl $RDH &>/tmp/rhd.log
		if [ ! -e overview0.ps ]
		then
			rm -rf $DATA_TMP/*
			echo "IDL unable to process data"
			break
		fi
		for i in {0..3}
		do
		        convert -density 200 -flatten -rotate 270 -resize 460x327 overview${i}.ps $HTML_PICS/overview${i}_460.png &
	        	convert -density 200 -flatten -rotate 270 -resize 460x334 sp${i}.ps $HTML_PICS/sp${i}_460.png &

	       		convert -density 200 -flatten -rotate 270 overview${i}.ps $HTML_PICS/overview${i}.png &
		        convert -density 200 -flatten -rotate 270 sp${i}.ps $HTML_PICS/sp${i}.png &
			wait
		done
		if [ -e "if.ps" ]
		then
		        convert -density 200 -flatten -rotate 270 if.ps $HTML_PICS/if.png &
		        convert -density 200 -flatten -rotate 270 -resize 955x346 if.ps $HTML_PICS/if_955.png &
			wait
		fi
		#$SQL < overview.txt
		tail -n1  overview.txt >> $HTML_DIR/overview.txt
		rm -rf overview{0..3}.ps sp0.ps sp{0..3}.ps if.ps overview.txt blesklog.txt \
			${BNAME}.bin ${BNAME}.txt
		mv overview{0..3}.idl $IDL_TEMP/
		#zip $DATA_DIR_OUT/${BNAME:0:4}_${BNAME:4:2}/$BNAME.zip *
		#(nice -n 15 tar cjf $DATA_DIR_OUT/hsd_$BNAME.tar.bz2 ${BNAME}.bin ${BNAME}.txt) &
		nice -n 15 zip $DATA_DIR_OUT/hs_${BNAME}_pics.zip *.ps
		mv $DATA_DIR_IN/$FNAME $DATA_DIR_OUT

		cd $DATA_TMP
		rm -rf $DATA_TMP/$DIRNAME
	fi
	read -t 0.1 INPUT
done
