#!/bin/bash -
#===============================================================================
#
#         FILE: manage_comment_spool
#
#        USAGE: ./manage_comment_spool [subject] [message-id]
#
#  DESCRIPTION: Deals with comments in the spool area where they are dropped
#               by Thunderbird. This script is also designed to be run out of
#               Thunderbird when it turns on or off the LED on the Blinkt!
#               (using MQTT) and de-duplicates comments if necessary.
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: ---
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.0.3
#      CREATED: 2023-07-14 15:38:33
#     REVISION: 2023-12-24 16:00:05
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

SCRIPT=${0##*/}

VERSION="0.0.3"

STDOUT="/dev/fd/2"

#===  FUNCTION  ================================================================
#         NAME: alert
#  DESCRIPTION: Turn a LED on the Blinkt! host to an RGB colour
#   PARAMETERS: 1 - LED number 0..7
#               2 - RGB colour as 'R,G,B' values, default '0,0,0'
#      RETURNS: 1 on error, otherwise 0
#===============================================================================
function alert () {
    local LED="${1}"
    local RGB="${2:-0,0,0}"

    local BHOST="192.168.0.63"

    mosquitto_pub -h $BHOST -t pimoroni/blinkt -m "rgb,$LED,$RGB"

}

#===  FUNCTION  ================================================================
#         NAME: _usage
#  DESCRIPTION: Report usage
#   PARAMETERS: None
#      RETURNS: Nothing
#===============================================================================
_usage () {
    cat >$STDOUT <<-endusage
Usage: ./${SCRIPT} [-h] [-s] [subject] [message-id]

Version: $VERSION

Script to be invoked via Thunderbird to manage and report on the comment spool
area

Options:
  -h                    Print this help
  -s                    Silent mode, output less text about actions

Arguments:
    subject
    message-id
These are optional and are only provided when called by Thunderbir

Examples
  ./${SCRIPT} -h

endusage
    exit
}

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#
# Option defaults
#
SILENT=0  # not silent by default

#
# Process options
#
while getopts :hs opt
do
    case "${opt}" in
        h) _usage;;
        s) SILENT=1;;
        ?) echo "$SCRIPT: Invalid option; aborting"; exit 1;;
    esac
done
shift $((OPTIND - 1))

#
# Constants
#
BASENAME="$HOME/HPR/Comment_system"
LOGDIR="$BASENAME/logs"
LOG="$LOGDIR/$SCRIPT.log"
SPOOLDIR="$HOME/HPR/CommentDrop"

# The LED to light
LED=1

# Whether we're doing alerts
ALERTING=1

#
# We expect to be called with two arguments if called from Thunderbird,
# otherwise we'll make empty defaults.
#
if [[ $# -eq 2 ]]; then
    subject="$1"
    message_id="$2"
else
    subject=
    message_id=
fi

#
# Check the spool directory
#
declare -a EMAIL
mapfile -t EMAIL < <(find "$SPOOLDIR" -maxdepth 1 -name "*.eml" -printf '%p\n')

#
# Clear out files which end in '-1.eml' (or any single digit number), and tidy
# the array as well.
#
i=0
for m in "${EMAIL[@]}"; do
    if [[ "$m" =~ -[1-9].eml$ ]]; then
        unset "EMAIL[$i]"
        rm -f "$m"
    fi
    ((i++))
done

#
# If we have comments left we turn on the LED, otherwise we turn it off
#
comments="${#EMAIL[@]}"
if [[ $comments -eq 0 ]]; then
    [ "$SILENT" == 0 ] && echo "Nothing found"
    [ "$ALERTING" == 1 ] && alert $LED
    exit
else
    [ "$SILENT" == 0 ] && echo "Found $comments $(ngettext comment comments "$comments")"
    [ "$ALERTING" == 1 ] && alert $LED '0,255,128'
fi

#
# Log the call, but only if there were comments.  This includes the two
# arguments passed by the filter, the subject and message-id.
#
echo "$SCRIPT $(date +'%F %H:%M:%S') '$$' '$subject' '$message_id'" >> "$LOG"

exit

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