#!/bin/bash
#	Script: gnss_run_gipsyx
#
#	Dependencies:
#		- teqc (3rd party binary www.unavco.org, must be in $PATH)
#		- raw2rinex (WebObs script located in the same directory)
#		- download_orbit (WebObs script located in the same directory)
#		- a WebObs grid for node's list and parameters (defined in
#		  the configuration file) that must be defined for each node:
#		               FID: station/marker code name
#		      FID_RECEIVER: receiver code name (overwrites Rinex header)
#		       FID_ANTENNA: antenna code name (overwrites Rinex header)
#
# 
# Authors: François BEAUDUCEL, Edgar LENHOF, Patrice BOISSIER
#          
# Created: 2019-02-11 at PVMBG, Bandung (Indonesia)
#          Based on Gipsy-Oasis version by Francois BEAUDUCEL (IPGP) and Ahmad Ali FAHMI (IRD),
#          Domerapi/WebObs Project, 2014.
# Updated: 2019-10-03

#Check lock file
LOCKFILE=/tmp/gnss_run_gipsyx.txt
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
	echo "already running"
	exit
fi

# Helper 
if [ $# -lt 2 ]; then
	echo " Syntax: gnss_run_gipsyx CONF DAYS [STATION] [-s \"STALIST\"] [-d yyyy/mm/dd,yyyy/mm/dd] [-force] [-lock]"
	echo " Description: runs the automatic GNSS process from raw files to position solution"
	echo "    Arguments:"
	echo "       CONF = configuration filename, e.g., /etc/webobs.d/gnss_run_gipsyx.rc"
	echo "       DAYS = number of days to process (from today)"
	echo "    Optionnal arguments:"
	echo "	     -s \"STA1 STA2...\""
	echo "          station code or station list with double quotes"
	echo "	        default is all nodes associated with local WebObs $GRID"
	echo "          or a list of nodes $NODES defined in .rc"
	echo "       -d yyyy/mm/dd,yyyy/mm/dd"
	echo "          choose days to start process; the DAYS argument can still be used to"
	echo "          process previous days from the selected ones, for instance:"
	echo "             gnss_run_gipsyx CONF 1 -d 2017/03/17,2018/08/05"
	echo "          will compute  2017/03/17, 2017/03/16, 2018/08/05 and 2018/08/04"
	echo "       -force"
	echo "          forces the process despite existence of final results"
	echo "       -lock"
	echo "          creates a lock file to prevent multiple process of gnss_run_gipsyx"
	echo ""
	exit 0;
fi

# reads parameters from bash configuration script
# variables that must be set: $GRID $FROM $DEST $GIPSYOPTIONS $TEQCOPTIONS
source "$1" || {
  echo "cannot read configuration file $1. Abort".
  exit 1
}

tmpdir=$(mktemp -d /tmp/gipsyx.XXXXXXXXXX)
rinex="$tmpdir/rinex"

PWD=$(pwd)
PROGDIR=$( cd "$( dirname "$0" )" && pwd )

ORBITS=( "flinn" "ql" "ultra" )

# gets the nodes parameters from WebObs
if [ "$GRID" != "" ]; then
	PROC="/etc/webobs.d/GRIDS2NODES/$GRID"
	NODES=$(grep -h "^$GRID\.FID|" $PROC.*/*.cnf|sed -E "s/.*FID\|//")
	NODESTABLE=$(grep -H "^$GRID\.FID|" $PROC.*/*.cnf|sed -E "s/.*\///"|sed -E "s/\.cnf:.*FID\|/\ /")
fi

if [ -z "$FMT" ]; then
	FMT='$FROM/$FID/$yyyy/$mm/$dd'
fi

TODAY=$(date -u +"%Y/%m/%d")
DAYS=$2
DAYLIST=$(for d in $(seq $DAYS -1 0);do date -u -d "$d day ago" +"%Y/%m/%d";done)

# boolean for forcing process (default value doesn't force)
FORCE=0

# Optionnal parameters
for (( i=1; i<=$#; i++)); do

    case ${!i} in

        -force) 
        declare FORCE=1
        echo "Force computation despites final orbits already exist";;

        -s) 
        j=$((i+1))
        IFS=' ' read -ra arrayStation <<< "${!j}"
        declare NODES=${arrayStation[@]};;

	-d)
        k=$((i+1))
        IFS=',' read -ra arrayDay <<< "${!k}"
        declare STARTDAYS=${arrayDay[@]}
        DAYLIST= $()
        for start in $STARTDAYS;do
                declare L=$(for d in $(seq $DAYS -1 0);do date -d "$d day ago $start" +%Y/%m/%d;done)
                DAYLIST=("${DAYLIST[@]}" "${L[@]}")     
        done
        DAYLIST=($(printf "%s\n" "${DAYLIST[@]}" | sort -u | tr '\n' ' '))
        declare DAYLIST=${DAYLIST[@]} #converting to proper format
        ;;

	-lock)
	# make sure the lockfile is removed when we exit and then claim it
	trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT
	echo $$ > ${LOCKFILE}
        
        esac
done


echo "*** GipsyX / WebObs $GRID GNSS File Processing ***"

for station in $NODES; do
	# cleans the string !
	FID=${station//[$'\t\r\n ']}
	echo ""
	echo "*** Processing files from station $FID for the last $DAYS days"

	# looks in node's parameters for possible antenna and receiver (will overwrite rinex header)
	if [ "$GRID" != "" ]; then
		ID=$(echo "$NODESTABLE" | awk "/$FID/ {print \$1}")
		receiver=$(grep -h "^$GRID\.FID_RECEIVER|" $PROC.$ID/$ID.cnf|sed -E "s/.*FID_RECEIVER\|//"|tr -d '\r')
		antenna=$(grep -h "^$GRID\.FID_ANTENNA|" $PROC.$ID/$ID.cnf|sed -E "s/.*FID_ANTENNA\|//"|tr -d '\r')
		echo "   WO ID = $ID - receiver = '$receiver' - antenna = '$antenna' (will use rinex header if empty)"
		if [ ! -z "$receiver" ]; then
			receiver=" -O.rt \"$receiver\""
		fi
		if [ ! -z "$antenna" ]; then
			antenna=" -O.at \"$antenna\""
		fi
	fi

	for ymd in $DAYLIST; do

		doy=$(date -d "$ymd" +"%j")
		sta=$(echo $FID | tr '[:upper:]' '[:lower:]')
		yyyy=${ymd:0:4}
		year=$yyyy
		mm=${ymd:5:2}
		dd=${ymd:8:2}

		# setting paths
		res="$DEST/$FID/$yyyy/$yyyy-$mm-$dd.$FID"
		gipsyres="$res.tdp"
		gipsylog="$res.log"

		if [[ $FORCE == 0 && -s "$gipsyres" ]]; then 
			echo "   file $gipsyres [flinn] already exists..."
		else
			# path of raw data: eval() will replace any variables in $FMT (from .rc)
			RAW=$(eval "echo $FMT")
			if [ ! -z "$(ls -Ad $RAW 2>/dev/null)" ]; then
				rm -rf $tmpdir/*
				# makes Rinex daily file from raw data (see raw2rinex script)
				$PROGDIR/raw2rinex "$RAW" $rinex $TEQCOPTIONS -O.mn \"$FID\" -O.mo \"$FID\" $receiver $antenna
				if [[ ! -z $VERBOSE || $? != 0 ]]; then
					echo "$PROGDIR/raw2rinex \"$RAW\" $rinex $TEQCOPTIONS -O.mn \"$FID\" -O.mo \"$FID\" $receiver $antenna"
				fi

				# real-time case: makes a 24h window from yesterday+today data
				if [[ "$REALTIME" == "Y" && "$ymd" == "$TODAY" ]]; then
					
					rinex1=$tmpdir/rinex1 # 2 days ago
					rinex2=$tmpdir/rinex2 # yesterday
					rinex3=$tmpdir/rinex3 # today
					
					declare ORBITS=( "ultra" ) #reaffect orbit value because only ultra can be used for realtime

					yesterday=$(date -u -d "1 day ago" +"%Y/%m/%d")
					two_days_ago=$(date -u -d "2 day ago" +"%Y/%m/%d")
					echo "   Real-time case: Appending $two_days_ago, $yesterday and $TODAY to process 30h of data."

					# converting yesterday rinex
                                        doy=$(date -d "$yesterday" +"%j")
                                        yyyy=${yesterday:0:4}
                                        mm=${yesterday:5:2}
                                        dd=${yesterday:8:2}
                                        RAW2=$(eval "echo $FMT")
					echo "$RAW2"
					$PROGDIR/raw2rinex "$RAW2" $rinex2 $TEQCOPTIONS -O.mn \"$FID\" -O.mo \"$FID\" $receiver $antenna
					if [[ ! -z $VERBOSE || $? != 0 ]]; then
						echo "$PROGDIR/raw2rinex \"$RAW2\" $rinex2 $TEQCOPTIONS -O.mn \"$FID\" -O.mo \"$FID\" $receiver $antenna"
					fi
					

					#converting 2 days ago rinex
		                        doy=$(date -d "$two_days_ago" +"%j")
                                        yyyy=${two_days_ago:0:4}
                                        mm=${two_days_ago:5:2}
                                        dd=${two_days_ago:8:2}
                                        RAW1=$(eval "echo $FMT")
					echo "$RAW1"
                                        $PROGDIR/raw2rinex "$RAW1" $rinex1 $TEQCOPTIONS -O.mn \"$FID\" -O.mo \"$FID\" $receiver $antenna
                                        if [[ ! -z $VERBOSE || $? != 0 ]]; then
                                                echo "$PROGDIR/raw2rinex \"$RAW1\" $TEQCOPTIONS -O.mn \"$FID\" -O.mo \"$FID\" $receiver $antenna"
                                        fi

					mv $rinex $rinex3 #already converted rinex for today
					if [[ ! -z $VERBOSE || $? != 0 ]]; then
						echo "   mv $rinex $rinex2"
					fi                 
                                        
					endwindow=$(date -u -d "$DATA_DELAY ago" +"%Y%m%d%H%M%S")
					teqc -phc +quiet -e $endwindow -dh 30 $rinex1 $rinex2 $rinex3 > $rinex
					if [[ ! -z $VERBOSE || $? != 0 ]]; then
						echo "   teqc -phc +quiet -e $endwindow -dh 30 $rinex1 $rinex2 $rinex3 > $rinex"
					fi
				fi

				# makes GipsyX processing
				tdp="$tmpdir/smoothFinal.tdp"
				cd $tmpdir


				
				# makes a loop for different orbits precision: from Final to Ultra
				for orbit in "${ORBITS[@]}" ; do
					if [[ $orbit == "ql" && -s $gipsyres.$orbit && $FORCE == 0 ]]; then
						echo "   file $gipsyres [$orbit] already exists..."
						break
					else

						if [ "$ORBITSDIR" != "" ]; then #running Gipsy from local orbit

							case $orbit in
	
								flinn)
								declare product="Final";;
								ql)
								declare product="Rapid";;
								ultra)
								declare product="Ultra";;
							esac
							
							# calling download_orbit
							$PROGDIR/download_orbit 0 $ORBITSDIR -o $product -d $ymd $DOWNLOAD_OPTIONS

							if [ ! -e "$ORBITSDIR/$product/$yyyy/$yyyy-$mm-$dd.eo.gz" ]; then
								continue # if download not successfull go to next orbit
							fi

							cmd="gd2e.py -rnxFile $rinex -GNSSproducts $ORBITSDIR/$product $GIPSYOPTIONS > gd2e.log 2>&1"

						else #running Gipsy from direct download
							cmd="gd2e.py -rnxFile $rinex -GNSSproducts $orbit $GIPSYOPTIONS > gd2e.log 2>&1"
						fi

						echo "$cmd"
						eval $cmd
						rc=$?
						if [[ $rc == 0 && -s $tdp ]]; then
							mkdir -p "$DEST/$FID/$year"
							rm -f $gipsyres.*
							grep ".State.Pos.[XYZ]" $tdp | tail -n3 > $gipsyres
							echo "==> $gipsyres [$orbit] written."
							if [[ "$orbit" != "flinn" ]]; then
								mv $gipsyres $gipsyres.$orbit
							fi 
							break
						else
							echo "   $cmd"
							echo "   ** WARNING: Problem to process gd2e... May be orbit $orbit not yet available?"
						fi
					fi
				done
				mv -f gd2e.log $gipsylog
				gzip -f $gipsylog
			else
				echo "   no data to process in $RAW."
			fi
		fi
	done
done

echo "*************************************"

if [ -z $DEBUG ]; then 
	rm -rf $tmpdir
fi

rm -f ${LOCKFILE}
