#!/bin/bash -
#===============================================================================
#
#         FILE: do_update_reservations
#
#        USAGE: ./do_update_reservations <epno>
#
#  DESCRIPTION: Script to update the status in the 'reservations' table after
#               a show has been processed.
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: ---
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.0.6
#      CREATED: 2022-04-11 09:36:21
#     REVISION: 2023-06-14 23:24:42
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

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

# shellcheck disable=SC2034
VERSION="0.0.6"

STDOUT="/dev/fd/2"

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

#
# Colour codes
#
define_colours

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

Version: $VERSION

Script to update the status in the 'reservations' table after a show has been
processed.

Options:
  -h            Print this help
  -d            Dry-run mode. Reports what it will do but doesn't do it
  -m            Monochrome mode - no colours

Arguments:
    shownumber

Examples
  ./${SCRIPT} -h
  ./${SCRIPT} -m 3112
  ./${SCRIPT} -d 3112
  ./${SCRIPT} -dm 3112
  ./${SCRIPT} 3112

endusage
    exit
}
#}}}

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

#
# Paths to files
#
BASENAME="$HOME/HPR/Show_Submission"

#
# Tools
#
BASECOM='curl -K ./.hpradmin_curlrc -s'
URL="https://hub.hackerpublicradio.org/cms/status.php"
QUERY="${BASECOM} ${URL}"

#
# Option defaults
#
COLOUR=1 # use colours by default
DRYRUN=0 # live mode by default

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

#
# 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
fi

epno="$1"

SHOWDIR="$BASENAME/shownotes/hpr${epno}"
STATUSFILE="$SHOWDIR/.status"

#
# Check the show in question exists
#
if [[ ! -d $SHOWDIR ]]; then
    echo "$SHOWDIR not found, can't continue"
    exit 1
fi

#
# Check the show is in the correct state of local processing
#
declare -a states
states+=( '+dir' )
if [[ -e "$SHOWDIR/shownotes.json" ]]; then
    states+=( '+shownotes' )
fi
if [[ -e "$SHOWDIR/hpr${epno}.html" ]]; then
    states+=( '+processed' )
fi
if [[ -e "$SHOWDIR/.uploaded" ]]; then
    states+=( '+uploaded' )
fi
echo "${green}Current state: ${states[*]}${reset}"

if ! grep -q -E '\+uploaded' <<<"${states[@]}"; then
    echo "The show is not in the +uploaded state"
    exit 1
fi

#
# Run the query with 'curl' and filter out this episode
#
reply="$(${QUERY} | grep -E "^[^,]+,$epno" )"
# echo "D> $reply"

#
# If we found the episode in the list we need to test further
#
if [[ -n $reply ]]; then
    echo "Found $epno in 'reservations'"

    #
    # Get the current state in the database by parsing the line returned.
    # Since Ken changed this out of the blue we now have:
    # 1. Epoch timestamp
    # 2. Episode number
    # 3. Episode date
    # 4. Key
    # 5. Status
    # 6. Email
    #
    if [[ $reply =~ ^([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),.*$ ]]; then
        state="${BASH_REMATCH[5]}"

        #
        # If it's aready in the desired state we're finished, otherwise we'll
        # set the new state
        #
        if [[ $state == 'METADATA_PROCESSED' ]]; then
            echo "Already marked ${blue}${state}${reset}"
        else
            echo "Ready for marking"
            command="${BASECOM} ${URL}?ep_num=${epno}&status=METADATA_PROCESSED"
            if [[ $DRYRUN -eq 1 ]]; then
                echo -e "Dry-run: would have run\n${yellow}$command${reset}"
            else
                echo "${yellow}$command${reset}"
                $command

                #
                # Change state/log what we did
                #
                echo "database" >> "$STATUSFILE" || \
                    { echo "Failed to update $STATUSFILE"; exit 1; }
            fi
        fi

    else
        echo "Couldn't parse '$reply'; aborting"
        exit 1
    fi
else
    #
    # We have no record of this show locally
    #
    echo "Not found $epno"
fi


exit

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