#!/bin/bash -
#===============================================================================
#
#         FILE: do_edit_shownotes
#
#        USAGE: ./do_edit_shownotes <field> <epno>
#
#  DESCRIPTION: Edit one of the fields often needing work in
#               shownotes.{json,txt}, writing the updates back to the HPR
#               server in case they are needed there.
#
#               ** Under development, not properly tested **
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: 2022-12-20: The shownotes.txt file is now obsolete
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.0.3
#      CREATED: 2022-12-09 21:52:29
#     REVISION: 2023-07-29 18:26:04
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

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

VERSION="0.0.3"

if [[ $# -ne 2 ]]; then
    echo "[${SCRIPT} ${VERSION}]: Usage: $SCRIPT field shownumber"
    exit
fi

#
# Collect arguments and validate them
#
field="${1,,}"
showno="$2"

field="${field// /}"
showno="${showno// /}"

if ! [[ $field =~ ^(tags|title|summary) ]]; then
    echo "Invalid field: $field"
    exit 1
fi

if ! [[ $showno =~ ^[0-9]+$ ]]; then
    echo "Invalid show number: $showno"
    exit 1
fi

#
# Constants, paths and files
#
BASENAME="$HOME/HPR/Show_Submission"
SHOWDIR="$BASENAME/shownotes/hpr${showno}"
# SHOWNOTES="$SHOWDIR/shownotes.txt"
# SNORIG="$SHOWDIR/shownotes.txt.orig"
JSONNOTES="$SHOWDIR/shownotes.json"
JSONORIG="$SHOWDIR/shownotes.json.orig"
ORIGIN="$SHOWDIR/.origin"
EDITSN="$BASENAME/edit_shownotes"
STATUSFILE="$SHOWDIR/.status"
DEST="hpr@hackerpublicradio.org:upload"
SSHPORT=22

#
# Collect the place to write results and the current MD5 sum of the JSON file
#
upload_dir=$(cat "$ORIGIN")
MD5_1=$(md5sum "$JSONNOTES")

#
# Run the editing program
#
echo "Editing $field for show $showno"
$EDITSN -field="$field" -episode="$showno"
RES=$?

#
# Normal exit (0) means something was done. Anything else either means the
# program aborted in a controlled way or there was an error.
#
if [[ $RES -eq 0 ]]; then
    echo "Edited show notes ok"

    MD5_2=$(md5sum "$JSONNOTES")
    if [[ $MD5_1 = "$MD5_2" ]]; then
        echo "The files were not changed"
        exit
    else
        echo "Copying $JSONNOTES to upload/$upload_dir/shownotes.json on the HPR server"
        echo "Copying $JSONORIG to upload/$upload_dir/shownotes.json.orig on the HPR server"
#         scp -P 22074 "$JSONNOTES" "$JSONORIG" "hpr@hackerpublicradio.org:upload/$upload_dir/"
        scp -P $SSHPORT "$JSONNOTES" "$JSONORIG" "$DEST/$upload_dir/"

        #
        # Update the status file
        #
        echo "metadata" >> "$STATUSFILE" || \
            { echo "Failed to update $STATUSFILE"; exit 1; }
    fi
else
    echo "Editing script ended prematurely"
fi

exit

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

