#! /bin/bash
# Last edited on 2010-07-08 18:39:06 by stolfilocal

usage="$0 [-original] [-absentOK] [-iconHeight NN] TITLE"

# Creates an index page "index.html" or "index-orig.html" for computer
# graphics homework hand-ins. This version is specialized for still
# images.
# 
# Reads files 
# 
#   rausrs.txt : login names and RA numbers of all registered students 
#   aus.txt : RA numbers of absentees
#   intro.html (if present) : blurb to be included in page, before results.
# 
# Rejects input from absentee students, unless "-absentOK" is given.
# For each non-absentee student, expects to find files
# 
#   ${ra}/main.pov - Main POV-ray file (edited by instructor)
#   ${ra}/main.png - GIF image.
#  
# The above files are the versions that were edited and/or rebuilt
# by the teacher. The original version of file "{FOO}.{BAR}",
# as turned in by the student, is assumed to be "{FOO}-orig.{BAR}".
# However, the original image may have extension ".gif" or ".jpg"
# instead of ".png".
# 
# If "-original" is given, makes an index "index-orig.html" for the
# "-orig" versions instead of the edited/rebuilt versions.
#
# The thumbnail version of file "{FOO}.{BAR}" or "{FOO}-orig.{BAR}"
# is created, if needed, with name "{FOO}-i.png" "{FOO}-orig-i.png". 

export PATH=".:tools:../tools:../../tools:../../../tools:../../../../tools:${PATH}"

# Name suffixes and button labels for "hot" and alternate versions:
hotsuf="";      hottxt="novo"
altsuf="-orig"; alttxt="orig"

# Options for {process-absentees}:
absentopt=( )

# Default icon height (pixels):
iconHeight=60

# TRUE if the derived files should be rebuilt as needed:
rebuild=1

while [[ ( $# -gt 0 ) && ( "/${1:0:1}" == "/-" ) ]]; do 
  if [[ ( $# -ge 1 ) && ( "/$1" == "/-absentOK" ) ]]; then
    absentopt=( "-absentOK" ); shift; 
  elif [[ ( $# -ge 1 ) && ( "/$1" == "/-original" ) ]]; then
    hotsuf="-orig"; hottxt="orig";
    altsuf="";      alttxt="novo";
    rebuild=0; shift; 
  elif [[ ( $# -ge 2 ) && ( "/$1" == "/-iconHeight" ) ]]; then
    iconHeight="$2"; shift; shift; 
  else
    echo "bad option: $1" 1>&2;
    echo "usage: ${usage}" 1>&2; exit 1
  fi
done

if [[ $# != 1 ]]; then
  echo "usage: ${usage}" 1>&2; exit 1
fi

title="$1"; shift;

rafile="rausrs.txt"
abfile="aus.txt"
hdrfile="intro.html"

htmfile="index${hotsuf}.html"

# Names of hot and alternate image files to be shown (minus extension):
imgname="main${hotsuf}"
altimgname="main${altsuf}"

# Remove files of absentees and provide "absent" picture for them:
if [[  -r ${abfile}  ]]; then 
  process-absentees ${absentopt[@]} `cat ${abfile} | egrep -v '^ *([#]|$)'`
fi

# Save old version of index page
if [[ -s ${htmfile} ]]; then
  /bin/mv ${htmfile} ${htmfile}~
fi

# Write index page header:
cat <<EOF >> ${htmfile}
<html>
<head>
<title>${title} (${hottxt})</title>
</head>
<body bgcolor="#cbcbcb">

<h1>${title} (${hottxt})</h1>
<h2><tt>[<a href="index${altsuf}.html">${alttxt}</a>&gt</tt></h2>

EOF

# Copy preformatted prologue:
if [[ -r ${hdrfile} ]]; then
  cat ${hdrfile} >> ${htmfile}
fi

# Get numbers of all registered students:
ras=( `cat ${rafile} | egrep -v '^ *([#]|$)' | gawk '//{print $2;}'` )

cat <<EOF >> ${htmfile}
<hr>
  <table cellspacing=1 cellpadding=1 border=0>
EOF

# Number of icons in current row:
n=0

for ra in ${ras[@]} ; do

  # Define, for student ${ra}:
  #
  #    ${povfile} = file name of "hot" source file.
  #    ${altpovfile} = file name of alternate source file.
  #    ${imgfile} = file name of the full "hot" image.
  #    ${iconfile} = file name of the iconic version of the "hot" image.
  #    ${altimgfile} = file name of the alternate image.
  #
  #    ${imgbutt} = the HTML fragment of the image button.
  #    ${altimgbutt} = the HTML fragment of the alternate image button.
  #    ${povbutt} = the HTML fragment of the source button.

  echo "=== ${ra} ====================================" 1>&2
  
  povfile="${ra}/main${hotsuf}.pov"
  altpovfile="${ra}/main${altsuf}.pov"

  if [[ ! ( -d ${ra} ) ]]; then
    # non-existant directory:
    echo "*** ${ra} missing or not directory" 1>&2
    povbutt="[×]"
    imgbutt="[×]"
    altimgbutt="[×]"
    imgfile="missing.png"
    altimgfile="missing.png"
    iconfile="missing-i.png"
  elif [[ -r ${ra}/.absent ]]; then
    # Absentee student:
    povbutt="[×]"
    imgbutt="[×]"
    altimgbutt="[×]"
    imgfile="absent.png"
    altimgfile="absent.png"
    iconfile="absent-i.png"
    # Ckeck if the POV-ray source exists, just for safety:
    if [[ -r ${povfile} ]]; then
      echo "*** ${ra}/.absent and ${povfile} both present" 1>&2; exit 1
    elif [[ -r ${altpovfile} ]]; then
      echo "*** ${ra}/.absent and ${altpovfile} both present" 1>&2; exit 1
    fi
  else 
    # Ckeck whether the POV-ray source exists:
    if [[ -r ${povfile} ]]; then
      povbutt='[<a href="'"${povfile}"'">fonte</a>]'
    else
      povbutt="[×]"
    fi

    # Get file name ${imgfile} of the "hot" image:
    if [[ ${rebuild} -ne 0 ]]; then
      # The image name is fixed:
      imgfile="${ra}/${imgname}.png"
      # Delete it if empty:
      if [[ -r ${imgfile} ]]; then
        if [[ ! ( -s ${imgfile} ) ]]; then
          echo "*** File ${imgfile} is empty, deleting it" 1>&2
          /bin/rm -f ${imgfile}
        fi
      fi
      # Try to rebuild it if needed:
      if [[ -r ${povfile} ]]; then
        # (Re)build image if necessary:
        if [[ ! ( -s ${imgfile} ) ]]; then
          echo "=== image ${imgfile} missing or empty, (re)building it ===" 1>&2
          ( cd ${ra} && make ${imgfile:t} ; echo " " )
          echo "=== done rebuilding ${imgfile} ===========================" 1>&2
        fi
      else
        echo "*** File ${povfile} is missing, can't rebuild ${imgfile}" 1>&2
      fi
      if [[ ! ( -s ${imgfile} ) ]]; then
        echo "*** File ${imgfile} is unreadable, missing, or empty" 1>&2
        imgfile="missing.png"
      fi
    else
      # Look for existing image of some type, default "missing.png":
      imgfile="missing.png"
      for ext in png gif jpg ; do
        imgcand="${ra}/${imgname}.${ext}"
        # Delete candidate if empty:
        if [[ -r "${imgcand}" ]]; then
          if [[ ! ( -s ${imgcand} ) ]]; then
            echo "*** File ${imgcand} is empty, deleting it" 1>&2
            /bin/rm -f ${imgcand}
          fi
        fi
        if [[ -s "${imgcand}" ]]; then
          imgfile="${imgcand}"; break
        fi
      done
    fi
    
    # If image exists, then get its icon, else use "missing-i.png":
    iconfile="${ra}/${imgname}-i.png"
    if [[ "${imgfile}" != "missing.png" ]]; then
      # Remove empty or outdated icon:
      if [[ -r ${iconfile} ]]; then
        if [[ ( ! ( -s ${iconfile} ) ) || ( ${imgfile} -nt ${iconfile} ) ]]; then
          /bin/rm -f ${iconfile} 
        fi
      fi
      # Make sure that the corresponding icon does exist:
      if [[ ! ( -s ${iconfile} ) ]]; then
        echo "=== creating thumbnail image for ${imgfile} ===" 1>&2
        convert ${imgfile} \
            -geometry "x${iconHeight}" \
            +profile '*' \
            -colors 254 \
          ${iconfile}
      fi
      imgbutt='[<a href="'"${imgfile}"'">img</a>]'
    else
      # Remove the corresponding icon, if any
      if [[ -r ${iconfile} ]]; then
        /bin/rm -f ${iconfile}
      fi
      # Use the "missing" image icon:
      iconfile="missing-i.png"
      imgbutt="[×]"
    fi

    # Get alternate image file, if any:
    altimgfile="missing.png"
    for ext in png gif jpg ; do
      altimgcand="${ra}/${altimgname}.${ext}"
      # Delete candidate if empty:
      if [[ -r "${altimgcand}" ]]; then
        if [[ ! ( -s ${altimgcand} ) ]]; then
          echo "*** File ${altimgcand} is empty, deleting it" 1>&2
          /bin/rm -f ${altimgcand}
        fi
      fi
      if [[ -s "${altimgcand}" ]]; then
        altimgfile="${altimgcand}"; break
      fi
    done
    if [[ ( -r ${altimgfile} ) && ( "${altimgfile}" != "missing.png" )  ]]; then
      altimgbutt='[<a href="'"${altimgfile}"'">'"${alttxt}"'</a>]'
    else
      altimgbutt="[×]"
    fi
  fi

  # Output the entry
  if [[ ${n} -eq 0 ]]; then
    echo "    <tr>" >> ${htmfile}
  fi
  cat <<EOF >> ${htmfile}
    <td nowrap> <a href="${imgfile}"><img src="${iconfile}"></a>&nbsp;&nbsp;<br><font size=+2><b>${ra}</b></font>&nbsp;<br>${povbutt}&nbsp;${altimgbutt}&nbsp;<br>&nbsp;</td>
EOF
  n=$(( ${n} + 1 ))
  if [[ ${n} -ge 5 ]]; then
    echo "    </tr>" >> ${htmfile}
    n=0
  fi
done

# Write index page trailer
if [[ ${n} -gt 0 ]]; then
  echo "    </tr>" >> ${htmfile}
fi

cat <<EOF >> ${htmfile}
  </table>
<hr>
</body>
</html>
EOF