#!/bin/bash - 
#===============================================================================
#
#         FILE: do_index
#
#        USAGE: ./do_index <epno>
#
#  DESCRIPTION: Makes an index.html file in the uploads directory of a show
#               for upload to the show's asset directory on the HPR server.
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: ---
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.0.5
#      CREATED: 2022-10-30 15:39:28
#     REVISION: 2022-12-17 17:38:00
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

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

VERSION="0.0.5"

STDOUT="/dev/fd/2"

#
# Load library functions (make_file_list, range_parse, cleanup_temp)
#
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

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

Version: $VERSION

Generates an 'index.html' file for a show with assets

Options:
  -h                    Print this help
  -d                    Select dry run mode

Arguments:
    shownumber

Examples
  ./${SCRIPT} 3112

endusage
    exit
}

#===  FUNCTION  ================================================================
#         NAME: _dryrun
#  DESCRIPTION: Output a dry run message
#   PARAMETERS: List of messages
#      RETURNS: Nothing
#===============================================================================
_dryrun () {
    local prefix="Dry run: "
    for msg in "$@"; do
        printf '%9s%s\n' "$prefix" "$msg"
        prefix=
    done
}
# }}}

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

#
# Option defaults
#
DRYRUN=0  # not dry run mode by default

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

#
# Check there's an argument after removing any options. Abort if not
#
if [[ $# -ne 1 ]]; then
    echo "${red}Missing shownumber argument${reset}"
    _usage
fi
ep="$1"
printf -v show 'hpr%04d' "$ep"

#
# Paths to files
#
BASEDIR="$HOME/HPR/Show_Submission"
SHOWDIR="$BASEDIR/shownotes/hpr${ep}"
RAWFILE="$SHOWDIR/shownotes.txt"
JSONFILE="$SHOWDIR/shownotes.json"
PICDIR="$SHOWDIR/uploads"
INDEXFILE="$PICDIR/index.html"
ASSETS="$SHOWDIR/.assets"               # Created in parse_JSON
PICLIST="$SHOWDIR/.pictures"            # Created in parse_JSON
STATUS="$SHOWDIR/.status"

#
# Check the show directory exists
#
if [[ ! -d $SHOWDIR ]]; then
    echo "$SCRIPT: ${red}Directory $SHOWDIR not found${reset}"
    exit 1
fi

#
# If no assets then don't continue
#
if [[ ! -e $ASSETS ]]; then
    echo "$SCRIPT: ${red}Asset file (.assets) not found in $SHOWDIR${reset}"
    exit 1
fi

#
# Do we already have an 'index.html'?
#
if [[ -e $INDEXFILE ]]; then
    echo "${red}There's already an 'index.html'${reset}"
    if [[ $DRYRUN -eq 0 ]] && ! yes_no 'Overwrite this file? %s ' 'No'; then
        echo "${red}Aborting!${reset}"
        exit 1
    fi
fi

#
# Make temporary files and set traps to delete them.
#
# TMP1 - HTML header
# TMP2 - HTML footer
#
TMP1=$(mktemp) || {
    echo "$SCRIPT: ${red}creation of temporary file failed!${reset}"
    exit 1
}
TMP2=$(mktemp) || {
    echo "$SCRIPT: ${red}creation of temporary file failed!${reset}"
    exit 1
}
trap 'cleanup_temp $TMP1 $TMP2' SIGHUP SIGINT SIGPIPE SIGTERM EXIT

#
# Parse these fields from the raw input file (shownotes.txt) into Bash
# variables so we can make an index.html later.
#
# Title='' Summary='' Host_Name=''
# eval \
#     "$(sed -n '/^\(Title\|Summary\|Host_Name\):/{s/^\([^:]\+\):\t/\1="/;s/$/"/;p}' "$RAWFILE")"

#
# Parse these fields from the JSON input file (shownotes.json) into Bash
# variables so we can make an index.html later.
#
Title='' Summary='' Host_Name=''
jqprog="@sh \"Host_Name=\(.host.Host_Name) Title=\(.episode.Title) Summary=\(.episode.Summary)\""
command=$(jq -r "$jqprog" "$JSONFILE")
eval "${command}"

#
# Make two HTML templates and two TTĀ² templates. We do this in dry-run mode
# too then throw them away!
#
# {{{
cat > "$TMP1" <<ENDHTML1
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="generator" content="pandoc">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  <meta name="author" content="$Host_Name">
  <title>$Title (HPR Show $ep)</title>
  <style type="text/css">code{white-space: pre;}</style>
  <!--[if lt IE 9]>
    <script src="https://html5shim.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <link rel="stylesheet" href="https://hackerpublicradio.org/css/hpr.css">
</head>

<body id="home">
<div id="container" class="shadow">
<header>
<h1 class="title">$Title (HPR Show $ep)</h1>
<h3 class="summary">$Summary</h3>
<h3 class="author">$Host_Name</h3>
<hr/>
</header>

<main id="maincontent">
<article>
<h3 id="index">Index</h3>
<ul>
ENDHTML1

cat > "$TMP2" <<ENDHTML2
</ul>
</article>
</main>
</div>
</body>
</html>
ENDHTML2
# }}}

#
# Make a simple index.html file. We use the .assets file and the .pictures
# list (if there is one) and read them into an aray and a hash. We can then
# generate HTML appropriate to their type.
#
if [[ $DRYRUN -eq 0 ]]; then
    #
    # Make an array of assets
    #
    if [[ -e $ASSETS ]]; then
        declare -a assets
        mapfile -t assets < "$ASSETS"
    else
        echo "$SCRIPT: ${red}No assets found!${reset}"
        echo "$SCRIPT: ${red}Show has no $ASSETS file!${reset}"
        exit 1
    fi

    #
    # Make a hash of pictures. It's not an error if there are none; we still
    # need to process assets.
    #
    if [[ -e $PICLIST ]]; then
        declare -A pix
        while read -er pic; do
            pix[$pic]=1
        done < "$PICLIST"
    else
        echo "$SCRIPT: ${red}No pictures found!${reset}"
        echo "$SCRIPT: ${blue}Processing $ASSETS only${reset}"
    fi

    #
    # Assemble the index from header, footer and a body of file/picture
    # references. If an asset is in the 'pix' hash then it's a picture, so we
    # generate different HTML than in the other case.
    # TODO: Do a better job with displaying the pictures! Maybe limit the
    # size? Who's going to be looking at this anyway? Could the image URL
    # contain a size I wonder?
    #
    (
        cat "$TMP1"
        for asset in "${assets[@]}"; do
            # Don't let the index point to itself!
            if [[ $asset == 'index.html' ]]; then
                continue
            fi
            if [ -e "$PICLIST" ] && [ "${pix[$asset]+set}" == 'set' ]; then
                printf '<li><img src="https://hackerpublicradio.org/eps/%s/%s" alt="%s"></li>\n' \
                    "$show" "$asset" "$asset"
            else
                printf '<li><a href="https://hackerpublicradio.org/eps/%s/%s">%s</a></li>\n' \
                    "$show" "$asset" "$asset"
            fi
        done
        cat "$TMP2"
    ) > "$INDEXFILE"

    #
    # Report what happened
    #
    if [[ -e $INDEXFILE ]]; then
        echo "${green}Generated index in $INDEXFILE${reset}"
    else
        echo "${red}Something went wrong; can't find $INDEXFILE${reset}"
    fi

    #
    # Set the status for this show
    #
    echo "index" >> "$STATUS"

else
    _dryrun "Would have generated index file ${yellow}$INDEXFILE${reset}"
fi

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