#/bin/bash

FTP_DIR="/mnt/ftp_cnes/CNES_to_scientifiques"

OUT_DIR="/mnt/raid/taranis/HFA_FM/AIT_CU_PLD"


BLESK="/mnt/raid/taranis/HFA_FM/AIT_CU/pustblesk.pro"
PYSASR="/mnt/raid/taranis/HFA_FM/AIT_CU/altevt.py"

shopt -s extglob

while true
do
	for run_dir in $(ls -d $FTP_DIR/+([0-9])/)
	do
		dir_nr=$(basename $run_dir)
		if [ ! -d $OUT_DIR/$dir_nr ]
		then
			date
			echo "New test run $dir_nr"
			if [ ! -d $OUT_DIR/$dir_nr ]; then mkdir $OUT_DIR/$dir_nr; fi
			tar_files=$(find $FTP_DIR/${dir_nr}/Donnees_decom/${dir_nr}_X/DATA_OUT/N0 \
				-regextype posix-extended -regex '.*/TAR_N0_12(24|25|26|27|28|29|30|31|32)_.*.DAT')
				#-execdir cp -t $OUT_DIR/$dir_nr {} +
			if [[ -z $tar_files  ]]
			then
				echo "No HFA files found!"
			else
				for tar_file in $tar_files
				do
					#echo "Downloading $tar_file"
					cp $tar_file $OUT_DIR/$dir_nr &>/dev/null
					if [[ "$?" -gt 0 ]]
					then
						echo "Can't copy file $tar_file from $dir_nr"
						rm -rf $OUT_DIR/$dir_nr
						sleep 30 
						continue
					fi
				done	
			fi
			if [ "$(ls -A $OUT_DIR/$dir_nr)" ]
			then
				pushd $OUT_DIR/$dir_nr &>/dev/null
				idl $BLESK > ${dir_nr}_blesklog.txt 2>/dev/null
				sr_dat=$(find . -name "*_1226_*.DAT")
				sa_dat=$(find . -name "*_1225_*.DAT")
				if [[ $sr_dat ]]
				then
					$PYSASR $sr_dat > ${dir_nr}_alt_evt.txt
				else
					if [[ $sa_dat ]]
					then
						$PYSASR $sa_dat > ${dir_nr}_alt_evt.txt
					fi	
				fi
				rm -rf sl.ps ew.ps ewspg.ps blesk.txt bleska_spectrogram.idl
				ls *.ps | parallel --no-notice ps2pdf {} {.}.pdf
				rm -rf *.ps
				popd &>/dev/null 
			fi
		fi
	done
	sleep 60
done
