#!/bin/sh
#
#   $1 specified local image under img/ and must be safe unquoted.
#   $2 is URL prefix for link to the static site, can be "".

# For a specified image $1 (local, under img/)
# if a .txt file is present returns HTML5 with schema.org microdata on stdout
# of the form:
#     i    with i linked to the .txt file and itemprop=discussionUrl
#
# or  i/src  with i linked to the .txt file as above
#            and src linked to the exetrnal source image
#                itemprop=isBasedOn if .txt file contains line of form
#
#     isBasedOn: <URL>
#
# Any isBasedOn URL should be safe to use as an unquoted attribute value;
# it will be quoted if not.  It must not contain spaces.

# Returns nothing on stdout if the specified source file or .txt do not exist.

# Specified source file and file.txt must exist and be non-zero length.
if [ ! -s "$1" -o ! -s "$1.txt" ]; then exit 0; fi

I="<a href=$2$1.txt itemprop=discussionUrl>i</a>"

# ISBASEDONURL is empty if absent, prefixed if needed, quoted if not safe.
ISBASEDONURL="`awk < $1.txt '/^ *isBasedOn: */ {if( $2 ~ /^[-_a-zA-Z0-9.:\/]*$/ ){print $2} else {printf("%c%s%c", 34, $2, 34)}}'`"
SRC=""
if [ "" != "$ISBASEDONURL" ]; then
    SRC="/<a href=${ISBASEDONURL} itemprop=isBasedOn>src</a>"
fi

echo "$I$SRC"
exit 0
