#!/bin/bash -
#===============================================================================
#
#         FILE: do_vim
#
#        USAGE: ./do_vim <epno>
#
#  DESCRIPTION: Run vim on notes for a show
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: The validate_html script failed because the HTML::Valid module
#               wasn't visible but the edit went ahead regardless. How to
#               handle such errors cleanly? Not found an answer yet.
#               2022-12-22: Added code to write to the .status file
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.0.8
#      CREATED: 2016-05-14 14:21:14
#     REVISION: 2022-12-22 17:08:22
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

SCRIPT=${0##*/}
#DIR=${0%/*}
VERSION="0.0.8"

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

BASENAME="$HOME/HPR/Show_Submission"
SHOWDIR="$BASENAME/shownotes/hpr${1}"
EXTRACT="$SHOWDIR/hpr${1}.out"
FORMAT="$SHOWDIR/.format"
VALIDATE="$BASENAME/validate_html"
ERRORS="$SHOWDIR/hpr${1}.err"
REPORT="$SHOWDIR/errors.txt"
PICTPL="$SHOWDIR/.pictures.tt2"
STATUSFILE="$SHOWDIR/.status"


#
# Sanity checks
#
[ -e "$VALIDATE" ] || {
    echo "$SCRIPT: HTML validator '$VALIDATE' not found"
    exit 1
}

if [[ ! -e $EXTRACT ]]; then
    echo "$SCRIPT: File not found: $EXTRACT"
    exit
fi

fmt=

#
# Set the Vim command from the declared format
#
if [[ ! -e $FORMAT ]]; then
    #
    # Default
    #
    vimcom=':set filetype=markdown'
else
    #
    # Define filetypes that Vim knows based on the names that arrive in the
    # form. All need work other than 'txt2tags'
    #
    fmt="$(cat "$FORMAT")"
    case $fmt in
        html5)
            fmt='html';;
        Markdown_GitHub | Markdown_Pandoc | markdown_standard | plain_text)
            fmt='markdown';;
        restructured_text)
            fmt='rst';;
        txt2tags)
            ;; # No action needed
        *)
            fmt='markdown';;
    esac
    vimcom=":set filetype=$fmt"
fi

#
# For html5 (now called 'html') run a validator on it. If this generates
# errors run Vim with a Quickfix window on the error file so the errors can be
# spotted and fixed.
#
if [[ $fmt == 'html' ]]; then
    #
    # The validator exits with False if there are errors
    #
    if ! $VALIDATE "$EXTRACT" > "$ERRORS"; then
        #
        # Did the validation script crash?
        #
        RES=$?
        if [[ $RES -ne 0 ]]; then
            echo "Problem running $VALIDATE; Edit aborted"
            exit
        fi

        #
        # HTML::Valid can put unwanted stuff in the error file. Not sure why.
        # We remove it with 'sed'. Only lines beginning with the path of the
        # input file are wanted.
        #
        # shellcheck disable=SC1117
        sed -i -ne "\#^$EXTRACT#p" "$ERRORS"

        #
        # Make an error file for reporting to the host, but only if it doesn't
        # already exist. Start with the HTML itself with line numbers and
        # follow with the error report with the file paths truncated.
        #
        if [[ ! -e $REPORT ]]; then
            nl -ba -w3 -s': ' "$EXTRACT" > "$REPORT"
            sed -e "s:^$BASENAME/::" "$ERRORS" >> "$REPORT"
        fi

        #
        # Run Vim on the errors with the option of running 'make' to
        # re-validate after correcting. We force Vim to open the quickfix
        # window so errors and warnings can be seen and edited.
        #
        # shellcheck disable=SC1117
        vim --cmd ":set makeprg=${VALIDATE}\ %" -c "$vimcom" \
            -c ':setlocal spell' -c:cope -q "$ERRORS"
        RES=$?
    else
        #
        # No validation errors
        #
        vim -c "$vimcom" -c ':setlocal spell' "$EXTRACT"
        RES=$?
    fi
else
    #
    # Not html5. If the picture template exists open it in a vertical split
    #
    if [[ -e $PICTPL ]]; then
        vim -c "$vimcom" -c ':setlocal spell' -O "$EXTRACT" "$PICTPL"
        RES=$?
    else
        vim -c "$vimcom" -c ':setlocal spell' "$EXTRACT"
        RES=$?
    fi
fi

if [[ $RES -eq 0 ]]; then
    echo "Edited $EXTRACT ok"

    #
    # Update the status file
    #
    echo "edited" >> "$STATUSFILE" || \
        { echo "Failed to update $STATUSFILE"; exit 1; }
else
    echo "Oops! Something went wrong!"
fi

exit

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