#!/bin/sh
# Plot all temp and humi data for the given ID from the compressed CSV.
# This will generate images out/$id-{temp,humi}.png

# TODO: use friendly name (eg 5s) from mapping in graphs.
# TODO: Exclude data (from CSV and PNG) before start time given in mapping.

# Usage:
#     $0 ID
#         Where ID is the sensor ID 1XXXXXX

ID="$1"
if [ "" = "$ID" ]; then
    echo "ERROR: missing sensor ID" 1>&2
    exit 1
fi

# Short name extract from map.
SN="-"
#kid,location,comment,starttime,endtime
#1644723,"5s","study / master bedroom",1733832000,1764979200
STMP="$(awk -F,<mapping.csv '$1~/^'"$ID"'/ {sn=$2;gsub(/"/,"",sn);print sn}')"
if [ "" != "$STMP" ]; then SN="$STMP"; fi

TEMPDATAFILEXZ="csv/$ID-temp.csv.xz"
if [ ! -s "$TEMPDATAFILEXZ" ]; then
    echo "ERROR: missing sensor temperature data file $TEMPDATAFILEXZ" 1>&2
    exit 1
fi
# Extract the data and pass on stdin to gnuplot.
xz -d < "$TEMPDATAFILEXZ" | \
    gnuplot \
        -e "ID='$ID'" \
        -e "outname='graphics/tmp/$ID-temp.png'" \
        -e "unit='C'" \
        -e "title='$SN temp'" \
        code/gnuplotTandRH.txt


HUMIDATAFILEXZ="csv/$ID-humi.csv.xz"
if [ ! -s "$HUMIDATAFILEXZ" ]; then
    # No RH% data may be acceptable, eg for 1gM.
    echo "INFO: no sensor humidity data file $HUMIDATAFILEXZ" 1>&2
    exit 0
fi
# Extract the data and pass on stdin to gnuplot.
xz -d < "$HUMIDATAFILEXZ" | \
    gnuplot \
        -e "ID='$ID'" \
        -e "outname='graphics/tmp/$ID-humi.png'" \
        -e "unit='%%'" \
        -e "title='$SN RH'" \
        code/gnuplotTandRH.txt
