#!/bin/bash

DATA_TMP="/tmp/delo2/tar"

DATA_DIR_IN="/mnt/raid/delos/delo2/tar"
#DATA_DIR_OUT="/mnt/jaruska/blesky/delo/handy"
DATA_DIR_OUT="/mnt/raid/storage/ersa/tar"

BLESK="/home/prokop/scripts/pustblesk_ersa.pro"
IDL_TEMP="/home/prokop/idl_temp"

HTML_DIR="/var/www/html/ersa"
HTML_PICS="/var/www/html/ersa/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)

	if [ ! $(ls $DATA_DIR_IN/*.7z 2>/dev/null | wc -l) -gt 1 ]
	then
		sleep 2
		echo -n "."
		continue
	fi

	FNAME=$(ls -1 $DATA_DIR_IN | head -1)

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

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

		echo $BNAME

		#dd if=${BNAME}_1226.bin of=tmp_sr.bin bs=2088 count=54
		#dd if=${BNAME}_1227.bin of=tmp_sl.bin bs=2088 count=54

		#mv tmp_sr.bin ${BNAME}_1226.bin
		#mv tmp_sl.bin ${BNAME}_1227.bin

		cp $IDL_TEMP/bleska_spectrogram.idl .
		idl $BLESK &>/tmp/blesk.log
		if [ ! -e *_1224.txt ]
		then
			rm -rf $DATA_TMP/*
			echo "$$: IDL unable to process data" 1>&2 
			break
		fi
		if [ -f "sl.ps" ]
		then
			convert -density 200 -flatten -rotate 270 sl.ps $HTML_PICS/sl.png &
			convert -density 200 -flatten -rotate 270 -resize 380x164 sl.ps $HTML_PICS/sl380.png &
		fi
		if [ -f "${BNAME}_1227.ps" ]
		then
			psselect -p1 ${BNAME}_1227.ps sl_p1.ps
			convert -density 200 -flatten -rotate 270 -crop 1967x472+0+472 +repage -resize '50%' sl_p1.ps \
			$HTML_PICS/sl_spec.png &
		fi 
		if [ -f "ew.ps" ]
		then
			convert -density 200 -flatten -rotate 270 ew.ps $HTML_PICS/ew.png &
			convert -density 200 -flatten -rotate 270 -resize 380x164 ew.ps $HTML_PICS/ew380.png &
		fi
		if [ -f "ewspg.ps" ]
		then
			convert -density 200 -flatten -rotate 270 ewspg.ps $HTML_PICS/ewspg.png &
			convert -density 200 -flatten -rotate 270 -resize 600x389 ewspg.ps $HTML_PICS/ewspg600.png &
		fi
		#$SQL < overview.txt
		wait
		echo $BNAME $(tail -n1  blesk.txt) >> $HTML_DIR/overview.txt
		cat ${BNAME}_stat.log >> $HTML_DIR/blesklog.txt
		rm -rf *.log sl_p1.ps ew.ps ewspg.ps sl.ps blesk.txt *.dat
		mv bleska_spectrogram.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 7za a $DATA_DIR_OUT/ersa_${BNAME}_pics.7z *.ps *.txt *.asc
		mv $DATA_DIR_IN/$FNAME $DATA_DIR_OUT/ersa_${BNAME}.7z

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