#!/bin/sh
# Add favicon to header of HTML files.  A favicon is a favorites icon,
# which appears in a browser tab that is visiting the given HTML file.
# One use case is for javadoc-generated API documentation.
#
# Usage:
#   html-add-favicon <directory> <favicon.png>
# The arguments should be paths relative to the current working directory.
# Once this has been run, running it again has no effect (and does no harm).

# Originally from http://stackoverflow.com/questions/13112123/creating-javadoc-html-pages-that-use-a-favicon
# The original version had several limitations:
#  * If a directory does not contain any .html files, it creates a file named "*.html".
#  * It does not add a favicon to HTML files generated by the JDK 8 version of javadoc, which uses "<head>" instead of "<HEAD>".
#  * If run multiple times, it inserts the favicon multiple times.
#  * The mktemp command is not portable (it doesn't work on Mac OS, for example).
#  * It does not preserve file permissions.
#  * It changes file timestamps even on files that are not changed.
#  * It does not hasdle file names containing spaces.
# This version corrects these issues.

patchIt () {
  for f in "$1"/*.html ; do
    if [ -f "$f" ]; then     # if no .html files exist, f is literal "*.html"
      tmpfile=$(mktemp patch_favicon_XXXXX)
      # This creates tmpfile, with the same permissions as $f.
      # The next command will overwrite it but preserve the permissions.
      # Hat tip to http://superuser.com/questions/170226/standard-way-to-duplicate-a-files-permissions for this trick.
      \cp -p "$f" "$tmpfile"
      sed -e " s%<head>\$%<head><link rel=\"icon\" href=\"$2\" type=\"image/png\"/>%" "$f" > "$tmpfile"
      if ! cmp "$f" "$tmpfile" >/dev/null 2>&1
      then
        mv -f "$tmpfile" "$f"
      else
        rm -f "$tmpfile"
      fi
    fi;
  done ;
  for d in "$1"/* ; do
    if [ -d "$d" ]; then echo "descending to $d" ; patchIt "$d" "../$2" ; fi ;
  done
}

patchIt "$1" "$2"

#eof
