#!/bin/bash

DATA_STORAGE="/mnt/raid/storage/lofar/mill"

MILL_HIST="/home/prokop/idl_temp/lofar/ml_mill.idl"

MILL_PRO="/home/prokop/scripts/pust_mill.pro"

MILL_DIR="/mnt/raid/delos/delo6/mill/"

MILL_TMP_DIR="/tmp/delo6/mill"

HTML_PICS="/var/www/html/lofar/pics_d"
HTML_LOG="/var/www/html/lofar/mill.txt"
HTML_LOG_MAX="/var/www/html/lofar/ml_max.txt"


process_data() {
	echo processing $1
        #elmavan data parsing
        cd $MILL_TMP_DIR
        cp $MILL_HIST mill_data.idl

	python3 ~/scripts/mill_check.py *.csv > sorted.txt
	mv sorted.txt *.csv

        idl $MILL_PRO 2>/dev/null
        #convert -density 200 -flatten -rotate 270 -crop 1967x650+0+0 +repage *.ps[0] $HTML_PICS/el.png &

        convert -density 100 -flatten -rotate 270 mill.ps $HTML_PICS/mill.png

        mv -f mill_data.idl $MILL_HIST
	cat $MILL_TMP_DIR/mill.txt >> $HTML_LOG && rm $MILL_TMP_DIR/mill.txt

	nice -n 19 zip -r $DATA_STORAGE/ml_${1}_pics.zip ${1}_mill.ps \
	&& rm -rf $MILL_TMP_DIR/* && mv $MILL_DIR/ml_${1}.7z $DATA_STORAGE/
}

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

INPUT=""

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

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

        if [ -e $MILL_DIR/$FNAME ]
        then
		echo "Unpacking $FNAME"
		cd $MILL_TMP_DIR
		#tar xjf $ELM_DIR/$FNAME
		7za e $MILL_DIR/$FNAME
		echo "Processing ${FNAME:3:15}"
		process_data ${FNAME:3:15}
                #rm $LOG_DIR/$FNAME
        fi
	read -t 0.1 INPUT
done
