#!/bin/sh
# Logs (every few minutes) snapshot of Eddi stats from grid.
# Preserved as original JSON except:
#     * Stale data from a previous data is discarded.
#     * The serial number is removed.
#     * Stale repeat records are discarded.


##########
# May be used / adapted / etc without any promise of fitness for purpose
# under the terms of the Apache License Version 2.0, January 2004
#     http://www.apache.org/licenses/LICENSE-2.0
##########


# Usage:
#     $0 [-dryrun]
#
# With -dryrun no file outputs are written,
# and the log record is echoed to stdout.

# FIXME: sneaky extra feature, which may go away in future.
# On creating a new file (ie at the start of the day, midnight)
# if "sta":5 (and maybe "bsm":0 to ensure no other boost in progress)
# then send a boost cancel to force the state to 1.
FIXSTA5="true"

dryrun="false"
if [ "-dryrun" = "$1" ]; then
    dryrun="true"
    echo INFO: dryrun
    shift
fi

# Output live log directory.
LOGDIR=data/eddi/log/live
OUTFILEBASE=_heat-battery-target

# Compute UTC YYYYMMDD date to match data logging.
UTCDATE="`date -u +%Y%m%d`"
#ISOUTCDATETIME="`date -u +%Y-%m-%dT%H:%MZ`"
# Today's log file.
LOGFILE=${LOGDIR}/${UTCDATE}.log

# Gather the raw stats JSON line.
RAWSTATSRECORD="`sh script/myenergi/eddiStatsAll-netrc.sh`"
# Format/example:
#{"eddi":[{"sno":12345678,"dat":"05-02-2022","tim":"22:35:45","ectt1":"Internal Load","ectt2":"Grid","ectt3":"None","bsm":0,"bst":0,"cmt":254,"dst":1,"div":0,"frq":50.08,"fwv":"3200S3.048","pha":1,"pri":1,"sta":1,"tz":0,"vol":2439,"hpri":1,"hno":1,"ht1":"Tank 1","ht2":"Tank 2","r1a":0,"r2a":0,"rbc":0,"rbt":8,"tp1":127,"tp2":127}]}

# If empty raw stats, eg from a comms issue, complain and exit.
if [ "" = "$RAWSTATSRECORD" ]; then
    echo "ERROR: could not retrieve Eddi stats snapshot" 1>&2
    exit 1
fi

# Remove the serial number.
LOGRECORD=`echo "$RAWSTATSRECORD" | sed -e 's/"sno":[^,}]*\([,}]\)/"sno":0\1/'`

# UTC date in format in Eddi stats, to filter out old (not from today) records.
EDDIUTCDATE="`date -u +%d-%m-%Y`"
# Remove very stale records (not from today).
if [ "" = "`echo \"$LOGRECORD\" | egrep -s '\"dat\":\"'$EDDIUTCDATE'\"'`" ]; then
    echo "ERROR: Eddi stats snapshot is stale (not today)" 1>&2
    exit 1
fi

# If this is a duplicate record, reject it.
if [ -s "$LOGFILE" ]; then
    LASTRECORD="`tail -1 < $LOGFILE`"
    if [ "$LASTRECORD" = "$LOGRECORD" ]; then
        echo "ERROR: Eddi stats snapshot is stale (duplicate)" 1>&2
        exit 1
    fi
fi

if [ "false" = "$dryrun" ]; then
    if [ -f $LOGFILE ]; then /bin/chmod u+w $LOGFILE; fi

    # FIXME: fix bogus persistent status 5 (hot water store full).
    # Only do this just after midnight (when about to create a new logfile).
    if [ "true" = "$FIXSTA5" -a ! -f $LOGFILE ]; then
        if [ "" != "`echo \"$LOGRECORD\" | egrep -s '\"sta\":5[^0-9]'`" ]; then
            echo "INFO: resetting possibly-bogus persistent Eddi status 5" 1>&2
            sh script/myenergi/eddiBoost-netrc.sh 0
        fi
    fi

    echo $LOGRECORD >> $LOGFILE
    /bin/chmod a+r,o-wx $LOGFILE
else
    echo INFO: log record 1>&2
    echo $LOGRECORD 1>&2
fi

exit 0
