#!/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)
#		- 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
#		       FID_ANTENNA: antenna code name
#
# 
# Authors: Francois BEAUDUCEL (IPGP), Ahmad Ali FAHMI (IRD)
#          Domerapi/WebObs Project
# Created: 2014-01-29 at BPPTKG, Yogyakarta (Indonesia) for Gipsy-Oasis version
# Created: 2019-02-11 at PVMBG, Bandung (Indonesia) for GipsyX version
# Updated: 2019-07-01

if [ $# -lt 2 ]; then
	echo "       Syntax: gnss_run_gipsyx CONF DAYS [STATION] [-force]"
	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 "        STATION = station code or station list with double quotes (default = all nodes associated with $GRID)"
	echo "         -force = forces the process despite existence of final results"
	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
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\|/\ /")

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)

if [ "$3" != "" ]
then
	NODES="$3"
fi

if [ "$4" == "-force" ]
then
	FORCE=1
else
	FORCE=0
fi

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)
	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

	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}
		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
					yesterday=$(date -u -d "1 day ago" +"%Y/%m/%d")
					doy=$(date -d "$yesterday" +"%j")
					yyyy=${yesterday:0:4}
					mm=${yesterday:5:2}
					dd=${yesterday:8:2}
					RAW2=$(eval "echo $FMT")
					rinex1=$tmpdir/rinex1
					rinex2=$tmpdir/rinex2
					echo "   Real-time case: Appending $yesterday and $TODAY to process 24h of data."
					$PROGDIR/raw2rinex "$RAW2" $rinex1 $TEQCOPTIONS -O.mn \"$FID\" -O.mo \"$FID\" $receiver $antenna
					if [[ ! -z $VERBOSE || $? != 0 ]]; then
						echo "$PROGDIR/raw2rinex \"$RAW2\" $rinex1 $TEQCOPTIONS -O.mn \"$FID\" -O.mo \"$FID\" $receiver $antenna"
					fi
					endwindow=$(date -u +"%Y%m%d%H%M%S")
					mv $rinex $rinex2
					if [[ ! -z $VERBOSE || $? != 0 ]]; then
						echo "   mv $rinex $rinex2"
					fi
					teqc -phc +quiet -e $endwindow -dh 24 $rinex1 $rinex2 > $rinex
					if [[ ! -z $VERBOSE || $? != 0 ]]; then
						echo "   teqc -phc +quiet -e $endwindow -dh 24 $rinex1 $rinex2 > $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 == ${ORBITS[1]} && -s $gipsyres.$orbit ]]; then
						echo "   file $gipsyres [$orbit] already exists..."
						break
					else
						cmd="gd2e.py -rnxFile $rinex -GNSSproducts $orbit $GIPSYOPTIONS > gd2e.log 2>&1"
						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
