#!/bin/bash
#
# Script holding common utility functions relating to time handling.
#
# All functions use 'local' declarations to avoid contamination of
# and scripts that use these functions.
#
# Note that for values with leading zeros that we perform calculation on
# we have to explicitly force base 10 so bash doesn't interpret it as octal.
#

#
# Convert file cor_site_YYYY_DDD_HH_MM to gnu secs since 1970
#
name_to_secs()
{
    local FN="$1"
    local Y
    local D
    local H
    local M
    local SS

    # Calculate seconds from start of the year
    set ${FN//_/ }
    Y=$3
    let D=10#$4
    let H=10#$5
    let M=10#$6
    let SS="($D-1)*24*60*60+($H*60*60)+($M*60)"

    date -d "$Y-01-01 UTC $SS seconds" +"%s"
}

#
# Convert a date of format YYYY-DDD-SSSSS to gnu secs since 1970
#
yds_to_secs()
{
    local YDS="$1"
    local Y
    local D
    local S
    local OS
    
    # Extract the year, day and seconds fields, being careful about
    # octal/leading zeros for values we use in calculations
    set ${YDS//-/ }
    Y=$1
    D=10#$2
    S=10#$3

    # Calculate the seconds since the start of this year
    # D starts at 1 for Jan 1st, so adjust by -86400
    let OS=$D*86400+$S-86400

    # Use date to convert to gnu seconds since 1970
    date -d "$Y-01-01 UTC $OS seconds" +"%s"
}

#
# Convert seconds since 1970 into the specified format
#
# If format is not specified, YYYY-DDD HH:MM:SS is used
#
secs_to_fmt()
{
    local SS="$1"
    local FM="$2"

    if [ "X$FM" = "X" ];
    then
        FM="%Y-%j %T"
    fi

    date -d "1970-01-01 UTC $SS seconds" +"$FM"
}

#
# Convert seconds since 1970 into YYYY-DDD-SSSSS format.
#
# A specific function, as 'date' doesn't have an expansion
# for seconds since midnight and so secs_to_fmt cannot be
# used.
#
secs_to_yds()
{
    local SS="$1"
    local Y
    local D
    local H
    local M
    local S
    
    # Extract out the year, day and hh-mm-ss.  Be careful about
    # leading zeros for hh/mm/ss as we calculate with them later.
    set `date -d "1970-01-01 UTC $SS seconds" +"%Y %j %H %M %S"`
    Y=$1
    D=$2
    let H=10#$3
    let M=10#$4
    let S=10#$5

    # Calculate seconds since midnight
    let S=$S+$M*60+$H*3600

    # Add maximum needed leading zero padding
    S=0000$S

    # Output the appropriate format
    echo "${Y}-${D}-${S:0-5:5}"
}

#
# Convert a seconds count into an HH:MM display
#
secs_to_hm()
{
    local S=$1
    local H
    local R
    local M
    
    let H=$S/3600
    let R=$S-$H*3600
    let M=$R/60

    M=0$M

    echo "${H}:${M:0-2:2}"
}

#
# Convert a seconds count into an HH:MM:SS display
#
secs_to_hms()
{
    local S=$1
    local H
    local R
    local M
    
    let H=$S/3600
    let R=$S-$H*3600
    let M=$R/60
    let S=$R-$M*60
    
    M=0$M
    S=0$S
    
    echo "${H}:${M:0-2:2}:${S:0-2:2}"
}

#
# Get the date of the file in gnu secs since 1970
# Also returns the file size
#
get_file_info()
{
	stat -L -c "%Y %s" $1
}

#
# Convert file cor_site_YYYY_DDD_HH_MM to the rev number
#
name_to_rev()
{
    local FN="$1"
    local Y
    local D
    local H
    local M
    local SS
    local MS1
    local MS2
    local DL

    # Calculate seconds from start of the year
    set ${FN//_/ }
    DL=$2
    Y=$3
    let D=10#$4
    let H=10#$5
    let M=10#$6
    let SS="($D-1)*24*60*60+($H*60*60)+($M*60)"

    # Convert the date to epoch seconds.
    SS=`date -d "$Y-01-01 UTC $SS seconds" +"%s"`

    # Now calculate the most significant 5 digits for
    # the support range, and the previous (in case we
    # cross a boundary)
    MS1=${SS:0:5}
    let MS2=$MS1-1
    
    # Extract the appropriate ranges, and check for a match
    egrep "^($MS1|$MS2)" /var/smei/new/TelemProcess/log/contacts/*.txt | cut -f 2- -d ':' | while read r;
    do
        set -- $r

        RISE=$1
	FALL=$2
        REV=$3
        SITE=$4

	# Give some margin.  120 seconds seems to catch all the files
        let RISE=${RISE}-120
        let FALL=${FALL}+120

        if [ $RISE -gt $SS ];
        then
            continue;
        fi

        if [ $FALL -lt $SS ];
        then
            continue;
        fi

        echo $REV
        break
    done

    return 0
}

#
# missings_revs()
#
missing_revs()
{
    local REV_START=$1
    local REV_STOP=$2
    local REV_YEAR=$3

    cat /var/smei/new/TelemProcess/log/contacts/${REV_YEAR}_*.txt | \
	cut -f 3 -d ' ' 					  | \
	sort -n 						  | \
	csplit -q -f /tmp/mr.$$. - "%^${REV_START}\$%+1" "/^${REV_STOP}\$-1/" 2>/dev/null
    if [ $? != 0 ];
    then
	echo ""
	return 0
    fi
   
    cat /tmp/mr.$$.00 | tr '\n' ' '

    rm /tmp/mr.$$.00 /tmp/mr.$$.01
   
    return 0
}

# Return a list of files between two date/times
#
# Parameter 0: Time Start (seconds since epoch)
# Parameter 1: Time Stop  (seconds since epoch)
#
files_between()
{
	local T_START=$1
	local T_STOP=$2

	local CANDIDATES
	local FILES

	local T=$T_START
	local YD
	local F
	local FT

	while [[ $T -le $T_STOP ]];
	do
		YD=`secs_to_fmt  $T "%Y_%j"`

		CANDIDATES=`grep "$YD" /var/smei/new/TelemAcquire/rate/sftp_rate.VCID5 | cut -f 6 -d ' ' | tr "\n" " "`

		if [ "X$CANDIDATES" != "X" ];
		then
			for F in $CANDIDATES;
			do
				FT=`name_to_secs $F`
				if [ $FT -le $T_STOP -a $FT -ge $T_START ];
				then
					FILES="$FILES $F"
				fi
			done
		fi
		
		let T=$T+86400
	done

	echo -n $FILES
}

#
# Transfer status display
#

transfer_status()
{
    local FILE
    local SIZE
    local AS
    local RS
    local MSG
    local STATE
    local RATE
    local DELTA
    local NOW
    local START
    local ETA
    
    NOW=`date +%s`

    echo "<h2>Current Acquire Status</h2>"
    echo "<p></p>"
    echo "<div class=\"tc\">"
    echo "<table>"
    echo "<tr><th>Script</th><th>Current File Download Status</th><th>Received</th><th>Average Rate (kbyte/s)</th><th>ETA (mins)</th></tr>"

    STATE=`cat /var/smei/new/TelemAcquire/acquire/acquiring.nso`
    set $STATE X X
    FILE=$1
    SIZE=$2
    if [ -f "/var/smei/new/TelemAcquire/tmp/sftp_$FILE" ];
    then
        local RS=`stat -c "%s" "/var/smei/new/TelemAcquire/tmp/sftp_$FILE"`
	AS=${SIZE/(/}
        AS=${AS/)/}

        MSG="${RS}&nbsp;of&nbsp;${AS}"
	STATE=$FILE

	START=`cat "/var/smei/new/TelemAcquire/tmp/sftp_${FILE}_s"`
	let DELTA=$NOW-$START
	let RATE=$RS/$DELTA/1024

	let ETA=$AS-$RS
	let ETA=$ETA/$RATE/1024/60
    else
        MSG="&nbsp;"
        RATE="&nbsp;"
        ETA="&nbsp;"
    fi
    
    echo "<tr><td>NSO&nbsp;Celeste</td><td>$STATE</td><td>$MSG</td><td align=center>$RATE</td><td align=center>$ETA</td></tr>"

    STATE=`cat /var/smei/new/TelemAcquire/acquire/acquiring.nso.blazing`
    set $STATE X X
    FILE=$1
    SIZE=$2
    if [ -f "/var/smei/new/TelemAcquire/tmp/sftp_$FILE" ];
    then
        local RS=`stat -c "%s" "/var/smei/new/TelemAcquire/tmp/sftp_$FILE"`
	AS=${SIZE/(/}
        AS=${AS/)/}

        MSG="${RS}&nbsp;of&nbsp;${AS}"
	STATE=$FILE

	START=`cat "/var/smei/new/TelemAcquire/tmp/sftp_${FILE}_s"`
	let DELTA=$NOW-$START
	let RATE=$RS/$DELTA/1024

	let ETA=$AS-$RS
	let ETA=$ETA/$RATE/1024/60
    else
        MSG="&nbsp;"
        RATE="&nbsp;"
        ETA="&nbsp;"
    fi
    
    echo "<tr><td>NSO&nbsp;Blazing</td><td>$STATE</td><td>$MSG</td><td align=center>$RATE</td><td align=center>$ETA</td></tr>"

    echo "</table>"
    echo "</div>"
    echo "<p class=\"last\"></p>"
}
