#!/bin/sh
# Create status of CSV time series as (X)HTML table to paste into page.
# Eg run in top-level of dataset directory as:
# % sh code/statusHTML.sh >> ../../.16WW-2025-high-res-temp-and-RH-dataset.html
#
# Hides less-important right-most columns on narrow displays.
#
# May only urun in macOS because of specialised use of date command.

# Mapping file.
MAPPING=mapping.csv
# Format
#ID,short_name,comment,start_time_incl,end_time_excl 
#1644723,"5s","study / master bedroom",1733832000,1764979200
#1644724,"7h","hallway",1733832000,1764979200

if [ ! -s "$MAPPING" ]; then
    echo "ERROR: missing mapping file $MAPPING" 1>&2
    exit 1
fi

# URL protocol-relative prefix for this dataset in EOU.
DATASETROOTURL="//WWW.earth.org.uk/data/16WW2025HiResTempAndRH"
# CSV (compressed) file directory within dataset.
CSVDIR="csv"

echo '<table class="tb1">'
echo '<thead>'
echo '<tr><th>ID</th><th>Short Name</th><th>Comment</th><th>Variables</th><th class="dopt">Window Start (incl)</th><th class="dopt">Window End (excl)</th></tr>'
echo '</thead>'

IDs="$(awk -F, <"$MAPPING" '/^1/{printf("%d ",$1)}')"
for id in $IDs;
    do
    RECORD="$(egrep "^$id," <"$MAPPING")"

    printf '<tr>'
    printf '<td>%s</td>' "$id"

    SN="$(echo $RECORD | awk -F, '{print $2}' | sed -e 's/"//g')"
    printf '<td class="tac">%s</td>' "$SN"

    # Comment is assumed to be HTML-safe.
    COMMENT="$(echo $RECORD | awk -F, '{print $3}' | sed -e 's/"//g')"
    printf '<td>%s</td>' "$COMMENT"

    # Iterate through possible types and link to those present.
    printf '<td>'
    for t in temp humi;
        do
        BASENAME="$CSVDIR/$id-$t.csv.xz"
        if [ -s "$BASENAME" ]; then
            printf '<a href="%s">%s</a> ' "$DATASETROOTURL/$BASENAME" "$t"
        fi
        done
    printf '</td>'

    # Window start/end times.
    ST="$(echo $RECORD | awk -F, 'NF>3{print $4}')"
    STISO=""
    if [ "" != "$ST" ]; then
        STISO="$(date -r "$ST" -u -Iminutes | sed -e 's/+00:00/Z/')"
        printf '<td class="dopt"><time>%s</time></td>' "$STISO"
    else
        printf '<td></td>'
    fi
    ET="$(echo $RECORD | awk -F, 'NF>4{print $5}')"
    ETISO=""
    if [ "" != "$ET" ]; then
        ETISO="$(date -r "$ET" -u -Iminutes | sed -e 's/+00:00/Z/')"
        printf '<td class="dopt"><time>%s</time></td>' "$ETISO"
    else
        printf '<td></td>'
    fi

    echo '</tr>'
    done

echo '</table>'

exit 0
