#!/bin/bash -
#===============================================================================
#
#         FILE: thanks_to_hosts
#
#        USAGE: ./thanks_to_hosts [year]
#
#  DESCRIPTION: Generates HTML to be added to the Community News at the end of
#               the year in order to thank hosts contributing shows in that
#               year.
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: ---
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.0.1
#      CREATED: 2025-10-06 16:38:42
#     REVISION: 2025-10-06 18:06:12
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

#
# Process the year, either as an argument or as a default (the current year)
#
YEAR="${1:-}"
if [[ -z $YEAR ]]; then
    YEAR="$(date +%Y)"
else
    if ! [[ $YEAR =~ ^[0-9]{4}$ ]]; then
        echo "Invalid year: '$YEAR'"
        exit 1
    fi
fi

#
# Various constants
#
# Uncomment the first form and comment out the second form unless 'query2tt2'
# is in your path. It or a link to the script will need to be in the current
# directory.
#
# DBQUERY='./query2tt2'
DBQUERY="$(command -v query2tt2)"

#
# Files expected to be in the current directory, or which will be written
# there. These could be given full absolute paths if desired.
#
DB='hpr.db'
CONFIG='.hpr_sqlite.cfg'
QUERY='hosts_in_year.sqlite.sql'
TEMPLATE='hosts_list.tpl'
OUTPUT="hosts_in_year_${YEAR}.html"

# [Nothing should need editing below here]

#
# Start and end of the year
#
YRSTART="${YEAR}-01-01"
YREND="${YEAR}-12-31"

#
# Sanity checks
#
[ -e "$DBQUERY" ] || {
    echo "Unable to find '$DBQUERY'"
    exit 1
}
[ -e $DB ] || {
    echo "Unable to find '$DB'"
    exit 1
}
[ -e $CONFIG ] || {
    echo "Unable to find '$CONFIG'"
    exit 1
}
[ -e $QUERY ] || {
    echo "Unable to find '$QUERY'"
    exit 1
}
[ -e $TEMPLATE ] || {
    echo "Unable to find '$TEMPLATE'"
    exit 1
}

#
# Query the SQLite database
#
$DBQUERY \
    -config=$CONFIG \
    -query=$QUERY \
    -template=$TEMPLATE \
    -dbarg "$YRSTART" \
    -dbarg "$YREND" \
    -def "year=${YEAR}" \
    -out="$OUTPUT"
RES=$?

#
# Deal with failures
#
if [[ $RES -eq 0 ]]; then
    echo "HTML written to $OUTPUT"
else
    echo "Problem generating HTML"
fi
exit $RES

# vim: syntax=sh:ts=8:sw=4:ai:et:tw=78:fo=tcrqn21

