#!/bin/bash
#
# 'makealbum-multipages.sh'
#
# A script to prepare a multi-page HTML "album" of digital pictures.
# This script does NOT perform any image conversion - use "makealbum.sh"
# for that. It "merely" ;-) prepares the HTML pages, and the data from
# can then be pasted into the resulting files.
#
# Arguments: Name of a plain-text file with filenames.
#            you need to create this file manually, e.g.:
#
#     for i in `seq 12 20`; do echo 200803${i}; done
#     ... and then edit the list:
#     20080310-12
#     20080313
#     20080314
#     20080315
#     20080316
#     20080317
#     20080318
#     20080319-20
#
# -----------------------------------------------------------------
# History:
#   2008-01-21, JHa, first draft.
#   2008-01-22, JHa, operational.
#   2008-04-03, JHa, some refinements and fixes.
#   2008-05-20, JHa, improved CSS.
#   2008-07-23, JHa, small bugfix in directory creation
# -----------------------------------------------------------------
# Copyright (c) 2008 Joerg Hau <joerg.hau(at)dplanet.ch>.
#
# Slideshow based on a script from http://www.ricocheting.com/,
# improved to support titles etc. by Florian Grosse-Coosmann.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# -----------------------------------------------------------------

# - directory structure will have one "index.html"
# - other HTML filenames are date-code (e.g. 20080310.html, 20080311.html, ...)

BDIR="../"				    # target base directory
FILE_CSS="style/style.css"
FILE_JS="style/slideshow.js"

# Some personal data (for copyright notice etc.)
#
NAME="Joerg Hau"			        # who?
EMAIL="joerg.hau&#64;dplanet.ch" 	# guess what ;-)

# these will be overwritten anyway
#
MYTITLE="Dummy Title"
KEYWORDS="please,enter,your,keywords,here"

#
# --- (usually) no user adjustable parts below this line :-)
#

# -----------------------------------------------------------------
# subroutine to check for some required executables
# argument: (list of) programs to test for
# will exit with rc=1 if any program was not found
# !!! Not every version of 'which' behaves the same !!!
# -----------------------------------------------------------------
function checkfor()
{
for i in $*; do
    PROG=`which $i`
    if [ -x "$PROG" ] ; then
        shift
    else
        echo "'$i' command not found, exiting."
        exit 1
    fi
done
}


# ------------------------------------------------------------
# subroutine to check error status of last command
# argument: error message
# will exit with rc=1 if errorlevel was not 0
# ------------------------------------------------------------
function errcheck()
{
if [ $? != 0 ]; then
    echo "Abort: $1, status: $?"
    exit 1
fi
}


# ------------------------------------------------------------
# verify if a directory is existing and accessible
# - if it does not exist, create ist.
# - arguments: $1 = path/to/directory
# ------------------------------------------------------------
function checkdir()
{
if [ ! -d $1 ] ; then
    mkdir -p $1 || errcheck "Error during creation of '$1'"
fi
if [ ! -r $1 ] ; then
    errcheck "'$1' exists but is not readable"
fi
}


# -----------------------------------------------------------------
# subroutine to "rebuild" date string from filename
# e.g. "/path/to/20071030.html" becomes "2007-10-30"
# argument: full pathname
# -----------------------------------------------------------------
function maketitle()
{
D=${1%.*}       # strip extension
D=${D##*/}      # strip path

if [ "$D" != "index" ] ; then   # only if not index.html
    Y=`echo $D | cut -c 1-4`
    M=`echo $D | cut -c 5-6`
    D=`echo $D | cut -c 7- | sed 's/-/\//'`	# replace dash by slash, if present
    TITLE="${MYTITLE}: ${Y}-${M}-${D}"
else                            # this is index.html
    TITLE="${MYTITLE}"
fi
}


# -----------------------------------------------------------------
# subroutine to create slideshow javascript (stand-alone)
# argument: name of outfile
# -----------------------------------------------------------------
function makejs()
{
cat << EOF >> ${1} || errcheck "Error in function makejs() during creation of '$1'"
<!-- slideshow from http://www.ricocheting.com/js/, improved by Florian Grosse-Coosmann  -->
<!-- this is Free Software; you can redistribute it and/or modify it under the terms of the GNU General Public License -->
<!-- start
  var x = 0;
  var pictureTitle = null;

  function rotate(num) {
    var opt, star, name, file, h;
    x = num % document.slideForm.slide.length;
    if ( x < 0) {
      x = document.slideForm.slide.length-1
    };
    opt = document.slideForm.slide.options[x].value;
    star = opt.lastIndexOf("*");
    name = opt.substr(0, star);
    file = opt.substr(star + 1);
    document.images.show.src = file;
    /* finally assign 'name' as the title somewhere */
    document.slideForm.slide.selectedIndex = x;
    if (pictureTitle == null) {
      pictureTitle = document.getElementById("picturetitle");
    }
    if (pictureTitle != null) {
      pictureTitle.innerHTML = name;
      /* alternatively use
       * pictureTitle.firstChild.data = name;
       */
    }
  }
  function apRotate() {
    if (document.slideForm.slidebutton.value == "Stop") {
      rotate(++x);
      window.setTimeout("apRotate()", 5000);
    }
  }
//end -->
EOF
}


# -----------------------------------------------------------------
# subroutine to create slideshow javascript (embedded in HTML file)
# argument: name of outfile
# -----------------------------------------------------------------
function makejs2()
{
cat << EOF >> ${1} || errcheck "Error in function makejs2() during creation of '$1'"
<h2><a name="slideshow">Slideshow</a></h2>
<form name="slideForm">
  <select name="slide" onChange="rotate(this.selectedIndex);">
    <script type="text/javascript">
    <!--
      for (i = 0; i < document.images.length; i++) {
      	document.write("<option value=\"" + document.images[i].name + "*" + document.images[i].alt + "\">" + document.images[i].name + "</option>");
      }
    //-->
    </script>
  </select>

  <input type=button onclick="rotate(0);" value="|&lt;&lt;" title="Jump to beginning">
  <input type=button onclick="rotate(x-1);" value="&lt;" title="Last Picture">
  <input type=button name="slidebutton" onClick="this.value=((this.value=='Stop')?'Start':'Stop');apRotate();" value="Start" title="Autoplay">
  <input type=button onclick="rotate(x+1);" value="&gt;" title="Next Picture">
  <input type=button onclick="rotate(this.form.slide.length-1);" value="&gt;&gt;|" title="Jump to end">
</form>

<script type="text/javascript">
<!--
  document.write("<p><img src=\"" + document.images[0].alt + "\" alt=\"current image\" name=\"show\"></p>");
  document.write("<p id=\"picturetitle\">" + document.images[0].name + "</p>");
//-->
</script>
EOF
}


# -----------------------------------------------------------------
# subroutine to create css file (stand-alone)
# argument: name of outfile
# -----------------------------------------------------------------
function makecss()
{
cat << EOF >> ${1} || errcheck "Error in function makecss() during creation of '$1'"
/* CSS Style sheet, conform to CSS Version 2 */
/* Author and copyright: Joerg Hau <joerg.hau(at)dplanet.ch> */

body	{
	font-family: verdana,helvetica,arial;
	font-style:normal;
	color:#000000;
	background-color:#ffffff;
	margin: 1em;
	}

p,pre,ol,ul,form {
	margin-left: 10%;
	}

p.warn {
    	font-weight:bold;
    	color:#ff0000;
        border: solid red 1px;
        padding:0.5em;
    	}

h1,h2 {
	color: #555555;
	background-color: #ffffff;
	font-weight:bold;
	margin-top:1.1em;
	border-bottom: solid 3px #555555;
	}

h2	{
	border-bottom: solid 1px #111111;
       	padding: 0.2em;
	}

h3,h4 	{
	color: #555555;
        margin-left: 10%;
        margin-top: 1.5em;
       	margin-bottom: 0.5em;
        background-color: #eeeeee;
      	padding: 0.2em;
	border-left: solid 1px #111111;
	border-top: solid 1px #111111;
        }

tt,pre 	{
	font-family: courier-new, courier;
	color:#008800;
	}

.ext	{
	list-style-image:url("off.png");
	}

.table	{
	background-color: #ffffff;
	color: #000000;
	vertical-align: top;
	font-family: verdana,helvetica,arial;
	font-style:normal;
	}

.tablehdr {
	background-color: #efefef;
	color: #555555;
	vertical-align: middle;
	font-weight:bold;
	font-family: verdana,helvetica,arial;
	}

.tablehi {
	background-color: #efefef;
	color: #000000;
	text-align:right;
	vertical-align: top;
	font-weight:bold;
	font-family: verdana,helvetica,arial;
	font-style:normal;
	}

.tablelo {
	color: #000000;
	vertical-align: top;
	font-family: verdana,helvetica,arial;
	font-style:normal;
	}

.footer	{
	color: #000000;
	vertical-align: top;
	font-family: verdana,helvetica,arial;
	font-style:normal;
	font-size: small;
	text-align:right;
	margin-top:1.1em;
	margin-left: 0%;
	border-top: solid 1px #555555;
	}

.active_page {
    background:#0000aa;
    color:#FFFFFF;
    padding-left:2px;
    padding-right:2px;
    }

a:link 	{ color: #0000aa; text-decoration:none }
a:visited { color: #775500; text-decoration:none }
a:hover	{ color: #0000dd; background-color:#dddddd;text-decoration:underline }
EOF
}


# -----------------------------------------------------------------
# subroutine to create links to other documents
# argument: name of outfile
# -----------------------------------------------------------------
function makelinks()
{
# loop through the filelist and create the hyperlinks
# (will not work correctly for the index.html file, but that's a special file anyway ...)
#
echo "<p>" >> ${1} || errcheck "Error in function makelinks()"
echo "<a href=\"index.html\">Back to main index</a> |"  >>${1}

for i in `cat $INFILE` ; do
    code=`echo ${i} | cut -c 7- `		# day code only
	fnam=`echo ${i} | sed 's/\//-/'`	# filename 
    if [ "${BDIR}/${i}.html" == "${IDX}" ] ; then
        # do not hyperlink to the document itself ;-)
        echo "<span class="active_page">$code</span> |"  >>${1}
    else
        echo "<a href=\"${fnam}.html\">${code}</a> | " >>${1}
    fi
done
echo "<a href=\"#slideshow\">Slideshow</a> " >>${1}
echo "</p>" >>  ${1}
}


# -----------------------------------------------------------------
# The main script starts here :-)
# -----------------------------------------------------------------

# if script is called w/o arguments, give usage instructions
#
if (( $# < 1 )) ;  then
    echo "Syntax: ${0##*/} listfile"
    exit 1
fi

# check if file is accessible and readable
#
INFILE=$1;
if [ ! -r $INFILE ] ; then
  echo "Cannot read '$INFILE' !"
  exit 1
fi

# check for some mandatory stuff
#
checkfor sed awk echo mkdir date

# obtain date stuff year from actual date
#
eval "`date "+DATE=%Y%m%d
              YEAR=%Y
              MONTH=%m
              DAY=%d"`"

# ask for target directory
#
TMP=$BDIR
read -p "Base directory for file structure (no spaces, default is '$BDIR') ?  " BDIR
if [ -z $BDIR ] ; then       # empty string?
    BDIR=$TMP                    # copy back
fi

# get some info
#
read -p "Title for this story?  " MYTITLE
read -p "Keywords for this story? (comma separated) " KEYWORDS

# create directory, javascript and css files
#
checkdir ${BDIR}/${IDIR}
checkdir ${BDIR}/style
makejs ${BDIR}/${FILE_JS}
makecss ${BDIR}/${FILE_CSS}

#####################################################################
# for all files in the list, run the following loop
#
for FILE in index `cat $INFILE | sed 's/\//-/'` ; do

IDX="${BDIR}/${FILE}.html"	    # name of the HTML file

maketitle ${IDX}

# avoid overwriting of an existing file by creating backup
# (attach a date-time stamp to the filename)
#
if [ -e ${IDX} ] ; then
    BKUP=${IDX}.`date +%Y%m%dT%H%M%S`
    echo -n "Preserving existing file ${IDX} as ${BKUP} ... "
    cp ${IDX} ${BKUP} || errcheck "Error during creation of '${BKUP}.'"
    echo "done."
fi

# Write header
#
cat <<EOF > ${IDX} || errcheck "Error during creation of '${IDX}.'"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
EOF

echo "<title>"${TITLE}"</title>" >> ${IDX}
echo "<!-- Copyright (C) "$YEAR" by "$NAME". All rights reserved. -->" >> ${IDX}
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-15\">" >> ${IDX}
echo "<meta name=\"generator\" content=\"makealbum-multipages.sh by joerg.hau(at)dplanet.ch\">" >> ${IDX}
echo "<meta name=\"keywords\" content=\"$KEYWORDS\">" >>${IDX}
echo "<meta name=\"author\" content=\"$NAME\">" >>${IDX}
echo "<link href=\"$FILE_CSS\" rel=\"stylesheet\" type=\"text/css\">" >>${IDX}
echo "<script src=\"$FILE_JS\" type=\"text/javascript\"></script>" >>${IDX}
echo "</head>" >> ${IDX}
echo "<body>" >> ${IDX}
echo "<h1>"${TITLE}"</h1>" >> ${IDX}

# add links to other documents
#
makelinks ${IDX}

# add code for header level 2
#
echo "<h2>"Description here"</h2>" >>${IDX}
echo "<p>"  >> ${IDX}
echo "Text goes here."  >> ${IDX}
echo "</p>" >> ${IDX}

cat << EOF  >> ${IDX}

<h3>Logistics</h3>
<ul>
<li></li>
<li></li>
<li>Total: xx&nbsp;km.</li>
</ul>

EOF

# add second part of code for slideshow
#
makejs2 ${IDX}

# repeat link bar here
#
makelinks ${IDX}

# finalise HTML code by adding a footer
#
echo -n "<p class=\"footer\">&copy; "$YEAR >> ${IDX}
echo -n " by <a href=\"&#109;ail&#116;&#111:$EMAIL\">$NAME</a>. " >> ${IDX}
cat <<'EOF' >> ${IDX}
All rights reserved.</p>
</body>
</html>
EOF

done
# end of the BIG loop
#####################################################################

exit 0

