#!/bin/bash -
#===============================================================================
#
#         FILE: do_brave
#
#        USAGE: ./do_brave <epno>
#
#  DESCRIPTION: Run the Brave browser to view completed notes
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: 2020-06-01: New version of Brave (now called 'brave-browser')
#               necessitates changes in how this script was originally
#               designed. The softlink between hpr????.out and hpr????.html
#               has been converted to a hard link.
#        NOTES: We use a link 'do_browser' to point to whichever script runs
#               the preferred browser. It's been Brave for several years now,
#               but we haven't changed this!
#               2022-12-22: We now write state changes to the file .status in
#               the show directory, so we need to do that here too. Also
#               changed to using the function library for cleanup_temp.
#               2024-10-17: Changed the logic around 'hpr????_full.html' by
#               using a TT² template to enclose the usual HTML fragment in
#               enough HTML to make it standalone. We have to get values from
#               'shownotes.json' and paass them into 'tpage' to do this, and
#               the end result is not the same as the one generated by
#               'do_pandoc'. The result looks better than using the HTML
#               fragment.
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.0.6
#      CREATED: 2016-03-20 15:22:29
#     REVISION: 2024-10-17 19:33:42
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

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

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

#
# Basic validation
#
if [[ $# -ne 1 ]]; then
    echo "Usage $SCRIPT shownumber"
    exit 1
fi

epno="${1}"

#
# Directories and files
#
BASENAME="$HOME/HPR/Show_Submission"
SHOWDIR="$BASENAME/shownotes/hpr${epno}"
RAWNOTES="$SHOWDIR/hpr${epno}.out"
HTML="$SHOWDIR/hpr${epno}.html"
FULLHTML="$SHOWDIR/hpr${epno}_full.html"
SHOWNOTES="$SHOWDIR/shownotes.json"
STATUSFILE="$SHOWDIR/.status"
FORMATFILE="$SHOWDIR/.format"
FORMAT="$(cat "$FORMATFILE")"

HTMLFILE="$FULLHTML"

#
# Check we have this template
#
FULLTPL="$BASENAME/make_fullnotes.tpl"
[[ -e $FULLTPL ]] || { echo "Unable to find template $FULLTPL"; exit 1; }

#
# Check we have this browser
#
BRAVE=$(command -v brave-browser)
[[ -v BRAVE ]] || { echo "Problem finding the Brave browser"; exit 1; }

#
# Taking a different approach with the 'full' html. If the format is known to
# be 'html5' there will not be one the first time we run this script. We will
# make 'hpr????_full.html' by enclosing the HTML "fragment" in 'hpr????.html'
# in a TT² template with HTML header and footer.
#
if [[ $FORMAT = 'html5' ]]; then
    #
    # Extract the fields we want from the JSON and make them Bash variables
    #
    declare _author _title _summary # Declare them for shellcheck
    jqprog='@sh "_author=\(.host.Host_Name) '
    jqprog+='_title=\(.episode.Title) '
    jqprog+='_summary=\(.episode.Summary)"'
    eval "$(jq -r "$jqprog" "$SHOWNOTES")"

    #
    # Feed the variables to the template to make the full HTML
    #
    tpage --define author="$_author" \
        --define title="$_title" \
        --define summary="$_summary" \
        --define body="$HTML" \
        "$FULLTPL" > "$FULLHTML"
else
    #
    # See above for how we make the 'full' notes if the host sent in HTML
    # notes. Here we have received notes that use one of the excepted markup
    # formats or are plain text (≡ Pandoc Markdown).
    #
    # If the 'full' HTML is not found (for unknown reasons) we look for
    # hpr????.html, which is a link to the notes from the form (hpr????.out),
    # and view that. If the link didn't get created (not sure why) we copy the
    # "raw" notes to a temporary file with an '.html' extension (TODO: we
    # could just make a link here). Otherwise we found nothing viewable.
    #
    if [[ ! -e $FULLHTML ]]; then
        if [[ -e $HTML ]]; then
            echo "No full HTML found, viewing $HTML instead"
            HTMLFILE="$HTML"
        elif [[ -e $RAWNOTES ]]; then
            echo "No files with ''.HTML' suffix, viewing raw notes"

            TMP1=$(mktemp '/tmp/notes_XXXXXX.html') || { echo "$SCRIPT: creation of temporary file failed!"; exit 1; }
            trap 'cleanup_temp $TMP1' SIGHUP SIGINT SIGPIPE SIGTERM EXIT

            cp "$RAWNOTES" "$TMP1"
            HTMLFILE="$TMP1"
        else
            echo "Nothing to view, giving up"
            exit
        fi
    fi
fi

#
# Open a parent instance of Brave (in the background), then open the HTML
# notes after a short delay, thereby ensuring they open in a tab rather than
# in another window.  Brave has great potential but documentation is a bit
# sparse.
# NOTE: We're using debug statements for the moment until this method is shown
# to be a good one.
#
# if [[ $(pgrep -u "$USER" -f '/usr/bin/brave-browser' -c) -eq 0 ]]; then
#     echo "D> Starting parent browser"
#     $BRAVE > /dev/null 2>&1 &
#     echo "D> Delaying ..."
#     sleep 3
# fi
#
# 2020-11-29 Looks like the parent + child model doesn't work any more (they
# keep changing this browser!). Also, just running the browser doesn't return
# to the command line any more so it seems to need to be in the background.
#
# echo "D> Starting browser tab"
echo "D> Starting browser itself"
$BRAVE "${HTMLFILE}" > /dev/null 2>&1 &
# $BRAVE "${HTMLFILE}&"
# $BRAVE "${HTMLFILE}"
RES=$?

if [[ $RES -eq 0 ]]; then
    #
    # Update the status file
    #
    echo "rendered" >> "$STATUSFILE" || \
        { echo "Failed to update $STATUSFILE"; exit 1; }
else
    echo "Oops! Something went wrong!"
    exit 1
fi

exit

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