#!/bin/bash -
# shellcheck disable=SC2317
#===============================================================================
#
#         FILE: do_report
#
#        USAGE: ./do_report [-h] [-D] [-m] [-s] [-Y] epno path_to_shownotes.json
#
#  DESCRIPTION: Script to be invoked after a show has been processed to make
#               a Matrix report.
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: ---
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.0.8
#      CREATED: 2022-09-07 15:27:29
#     REVISION: 2024-06-18 20:13:46
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

SCRIPT=${0##*/}
#DIR=${0%/*}

# shellcheck disable=SC2034
VERSION="0.0.8"

STDOUT="/dev/fd/2"

#
# Load library functions
#
LIB="$HOME/HPR/function_lib.sh"
[ -e "$LIB" ] || { echo "$SCRIPT: Unable to source functions"; exit 1; }
# shellcheck source=/home/cendjm/HPR/function_lib.sh
source "$LIB"

#
# Colour codes
#
define_colours

#{{{ Functions: --- _usage --- _verbose --- _silent ---
#===  FUNCTION  ================================================================
#         NAME: _usage
#  DESCRIPTION: Report usage
#   PARAMETERS: None
#      RETURNS: Nothing
#===============================================================================
_usage () {
    cat >$STDOUT <<-endusage
Usage: ./${SCRIPT} [-h] [-D] [-m] [-s] [-Y] shownumber

Version: $VERSION

Script to create and send a Matrix message about the processing of the show

Options:
  -h                    Print this help
  -D                    Run in debug mode where a lot more information is
                        reported
  -m                    Monochrome mode - no colours
  -s                    Silent mode, output less text about actions

Arguments:
    shownumber

Examples
  ./${SCRIPT} -h
  ./${SCRIPT} -m 3112
  ./${SCRIPT} -D 3112
  ./${SCRIPT} 3112

endusage
    exit
}

#===  FUNCTION  ================================================================
#         NAME: _verbose
#  DESCRIPTION: Writes a message in verbose mode
#   PARAMETERS: $1      message
#      RETURNS: Nothing
#===============================================================================
_verbose () {
    [ "$VERBOSE" -eq 0 ] && return
    for msg in "$@"; do
        printf '%s\n' "$msg"
    done
}

#===  FUNCTION  ================================================================
#         NAME: _silent
#  DESCRIPTION: Writes a message unless in silent mode
#   PARAMETERS: $1      message
#      RETURNS: Nothing
#===============================================================================
_silent () {
    [ "$SILENT" -eq 1 ] && return
    for msg in "$@"; do
        printf '%s\n' "$msg"
    done
}
#}}}

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

#
# Paths to files
#
BASENAME="$HOME/HPR/Show_Submission"
TPL="$BASENAME/shownotes/hpr%d/%s"
Q2CSV="$BASENAME/query2csv"

[ -e "$Q2CSV" ] || { echo "Unable to find '$Q2CSV'; aborting"; exit 1; }

#
# Option defaults
#
COLOUR=1 # use colours by default
SILENT=0 # not silent by default

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

DEBUG=${DEBUG:-0}
SILENT=${SILENT:-0}

#
# Cancel colours if requested
#
if [[ $COLOUR -eq 0 ]]; then
    undefine_colours
fi

#
# Check the argument after any options
#
if [[ $# -ne 1 ]]; then
    echo "$SCRIPT: ${red}Usage: $SCRIPT shownumber${reset}"
    exit 1
fi
show="$1"
# json="$2"

#
# Compute paths to show-specific files
#
# shellcheck disable=SC2059
{
printf -v json "$TPL" "$show" "shownotes.json"
printf -v assetfile "$TPL" "$show" ".assets"
printf -v statusfile "$TPL" "$show" ".status"
_DEBUG "Path to json = $json"
}

#
# Simplify checks
#
if [[ ! -e $json ]]; then
    echo "$SCRIPT: ${red}Unable to find $json${reset}"
    exit 1
fi

#-------------------------------------------------------------------------------
# Get the show details
#-------------------------------------------------------------------------------
#
# Extract JSON data and make Bash assignments which are then processed
# with 'eval'.
# Have to declare variables to avoid upsetting Shellcheck
#
declare host hostid email format
jqscript='host=\(.host.Host_Name) hostid=\(.host.Host_ID) '
jqscript+='email=\(.host.Host_Email) format=\(.metadata.POST.shownotes_format)'
commands=$(jq -r "@sh \"$jqscript\"" "$json")
eval "${commands}"

#
# The zero hostid needs checking
#
if [ "$hostid" -eq 0 ]; then
    _silent "${yellow}Checking host id 0 is valid${reset}"
    # Look up in database
    hid=$($Q2CSV "select hostid from hosts where host like '%${host}%'")
    # Use the host id we found if the zero id is wrong
    if [[ -n $hid ]]; then
        _silent "${yellow}Found the host name $host with id $hid${reset}"
        hostid=$hid
        newhost=""
        email=" (using $email)"
    else
        newhost="new host "
        email=" ($email)"
    fi
else
    newhost=""
    email=""
fi

#
# If the hostid is zero the email wasn't known (so maybe a new host) and we
# didn't find the name in the database (so treat them as new). We only report
# the email if it's a known host (by name) using a new address or if it's
# a new host.
#
# if [ "$hostid" -eq 0 ]; then
#     newhost="new host "
#     email=" ($email)"
# else
#     newhost=""
#     email=""
# fi

#
# If there are assets collect their names
# NOTE: now not used except as a non-blank string
#
if [[ -e $assetfile ]]; then
    # The sed expression confuses ShellCheck
    # shellcheck disable=SC2016
    assets="$(sort "$assetfile" | sed -ne 'H;${x;s/\n//;s/\n/, /g;p}')"
else
    assets=
fi

#
# Report the settings in debug mode
#
_DEBUG "Show number = $show" \
       "Host name   = $host" \
       "Host ID     = $hostid" \
       "Host email  = $email" \
       "Assets      = $assets"

#
# Handle backticks in the host string (Rho`n/Roan made me do it!)
#
if grep -q -E '`' <<<"$host"; then
    # shellcheck disable=SC2001 disable=SC2016
    host=$(sed -e 's/^\([0-9A-Za-z_`-]\+\)$/`\1`/' <<<"$host")
fi

#
# Generate the message we want to send
#
# shellcheck disable=SC2016
printf -v message 'Processed %s from %s`%s`%s. Format is *%s*.' \
    "$show" "$newhost" "$host" "$email" "$format"
if [[ -n $assets ]]; then
    # We have assets but were they sent?
    if grep -q -E '^assets' "$statusfile"; then
        message+=" Assets uploaded"
    else
        _silent "${yellow}Note: assets were found but not uploaded${reset}"
    fi
fi

#
# Send it, after checking
#
echo "Will run the following command:"
echo "${green}matrix-commander -z -m '$message'${reset}"
if yes_no 'OK to proceed? %s ' 'No'; then
    command="matrix-commander -z -m '$message'"
    eval "$command" || \
        { echo "Failed to invoke the command!"; exit 1; }

    #
    # Change state/log what we did, but only if we actually did it
    #
    echo "reported" >> "$statusfile" || \
        { echo "Failed to update $statusfile"; exit 1; }

fi

exit

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