#! /bin/bash
# Last edited on 2010-07-08 18:15:44 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
# animations.
# 
# Reads files 
# 
#   rausrs.txt : RA numbers and login names 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-m-0.0000.png - First frame
#   ${ra}/main-m-0.5000.png - Middle frame
#   ${ra}/main-m-1.0000.png - Last frame
#   ${ra}/main-m.gif - Animated gif
#   ${ra}/main-s.png - Strip with sample frames
# 
# If "-original" is given, makes an index "index-orig.html" for the
# "-orig" versions instead of the edited/rebuilt versions.
#  
# 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}".
#
# 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;

# Clock value of frame to use as icon (format "N.N"):
iconclock="0.0";
# iconclock="0.5";

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

# Number of icons per row:
iconsperrow=4

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 [[ $# -ne 1 ]]; then
  echo "\$# = $#  \$@ = [$@]" 1>&2;
  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 images to show (minus extension):
firstname="main-0.0000${hotsuf}"
middlename="main-0.5000${hotsuf}"
lastname="main-1.0000${hotsuf}"
stripname="main-s${hotsuf}"
movname="main-m${hotsuf}"
altmovname="main-m${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 [[ -e ${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}
  <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.
  #    ${stripfile} = file name of the "hot" filmstrip.
  #    ${movfile} = file name of the full "hot" movie.
  #    ${moviconfile} = file name of the iconic version of the "hot" movie.
  #    ${altmovfile} = file name of the alternate movie.
  # 
  #    ${frabutt} = the HTML fragment of the single-frame buttons.
  #    ${strbutt} = the HTML fragment of the filmstrip button.
  #    ${movbutt} = the HTML fragment of the hot movie button.
  #    ${altmovbutt} = the HTML fragment of the alternate movie 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
    frabutt="[×]"
    strbutt="[×]"
    movbutt="[×]"
    altmovbutt="[×]"
    povbutt="[×]"
    stripfile="missing.png"
    movfile="missing.png"
    moviconfile="missing-i.png"
    altmovfile="missing.png"
  elif [[ -r ${ra}/.absent ]]; then
    # Absentee student:
    frabutt="[×]"
    strbutt="[×]"
    movbutt="[×]"
    altmovbutt="[×]"
    povbutt="[×]"
    stripfile="absent.png"
    movfile="absent.png"
    moviconfile="absent-i.png"
    altmovfile="absent.png"
    # Ckeck if the POV-ray source exists, just in case:
    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

    # Default movie icon is "missing-i.png", eventually changed below:
    moviconfile="missing-i.png"
    moviconok=0

    # Create single-frame button string ${frabutt}:
    frabutt=""
    for fc in \
      ${firstname}/0.0 \
      ${middlename}/0.5 \
      ${lastname}/1.0 \
    ; do
      franame="${fc%/*}" 
      clock="${fc#*/}"

      # Get:
      #   ${frafile} = file name of selected full "hot" frame.
      #   ${fraiconfile} = file name of iconic versions of selected "hot" frame.
      #   ${clock} = clock value of the selected frame.
      
      # Look for frame image, of any type (defaults to "missing.png"): 
      frafile="missing.png"
      for ext in png gif jpg ; do
        # Candidate frame file to show:
        fracand="${ra}/${franame}.${ext}"
        # Remove candidate image if empty:
        if [[ -r "${fracand}" ]]; then
          if [[ ! ( -s ${fracand} ) ]]; then
            echo "file ${fracand} is empty, deleting it" 1>&2
            /bin/rm -f ${fracand} 
          fi
        fi
        # If it exists and is not empty, use it:
        if [[ -s "${fracand}" ]]; then
          frafile="${fracand}"; break
        fi
      done
      
      # Get thumbnail (icon) image for that frame image:
      fraiconfile="${ra}/${franame}-i.png"
      if [[ "${frafile}" != "missing.png" ]]; then
        # We do have a frame image:
        # Remove the thumbnail if empty or outdated:
        if [[ -r ${fraiconfile} ]]; then
          if [[ ( ! ( -s ${fraiconfile} ) ) || ( ${frafile} -nt ${fraiconfile} ) ]]; then
            /bin/rm -f ${fraiconfile} 
          fi
        fi
        # Make sure that the icon does exist:
        if [[ ! ( -s ${fraiconfile} ) ]]; then
          echo "=== creating thumbnail image for ${frafile} ===" 1>&2
          convert ${frafile} \
              -geometry "x${iconHeight}" \
              +profile '*' \
              -colors 254 \
            ${fraiconfile}
        fi
        frabutt="${frabutt}"'[<a href="'"${frafile}"'">'"${clock}"'</a>]'
      else
        # We do not have a frame image to show.
        echo "*** Files ${ra}/${franame}.{png,gif,jpg} are missing, unreadable, or empty" 1>&2
        # Remove the corresponding thumbnail, if any:
        if [[ -r ${fraiconfile} ]]; then
          /bin/rm -f ${fraiconfile}
        fi
        # Use the icon for "missing" image:
        fraiconfile="missing-i.png"
        frabutt="${frabutt}[×]"
      fi
      echo "  clock = ${clock} frame = ${frafile} icon = ${fraiconfile}" 1>&2
      
      # Save frame icon as movie icon:
      if [[ ( "${fraiconfile}" != "missing-i.png" ) && ( ${moviconok} -eq 0 ) ]]; then
        moviconfile="${fraiconfile}"
        if [[ "/${clock}" == "/${iconclock}" ]]; then moviconok=1; fi
      fi
    done

    # Get filmstrip file name (may have any extension)
    stripfile="missing.png"
    for ext in png gif jpg ; do
      stripcand="${ra}/${stripname}.${ext}";
      # Remove candidate image if empty:
      if [[ -r "${stripcand}" ]]; then
        if [[ ! ( -s ${stripcand} ) ]]; then
          echo "file ${stripcand} is empty, deleting it" 1>&2
          /bin/rm -f ${stripcand} 
        fi
      fi
      if [[ -s "${stripcand}" ]]; then
        stripfile="${stripcand}"; break
      fi
    done
    if [[ ( -s ${stripfile} ) && ( "${stripfile}" != "missing.png" ) ]]; then
      echo "*** File ${stripfile} is missing, unreadable, or empty" 1>&2
      strbutt='[<a href="'"${stripfile}"'">quadros</a>]'
    else
      strbutt="[×]"
    fi
    echo "  file strip = ${stripfile}"  1>&2

    # Get file name of "hot" movie:
    movfile="${ra}/${movname}.gif"
    if [[ ${rebuild} -ne 0 ]]; then
      if [[ -r ${povfile} ]]; then
        # (Re)build movie if necessary:
        if [[ ! ( -s ${movfile} ) ]]; then
          echo "=== (re)building movie ${movfile} ===" 1>&2
          ( cd ${ra} && make ${movfile:t} ; echo " " )
          echo "=== done rebuilding ${movfile} ===========================" 1>&2
        fi
      else
        echo "*** File ${povfile} missing, can't rebuild ${movfile}" 1>&2
      fi
    fi
    if [[ ! ( -s ${movfile} ) ]]; then
      echo "*** File ${movfile} is missing, unreadable, or empty" 1>&2
      movfile="missing.png"
    fi
    echo "  movie file = ${movfile}"  1>&2

    # Create "hot" movie button, or substitute "missing.png":
    if [[ "${movfile}" != "missing.png" ]]; then
      movbutt='[<a href="'"${movfile}"'">filme</a>]'
    else
      movbutt="[×]"
    fi

    # Get name of alternate movie file:
    altmovfile="${ra}/${altmovname}.gif"
    if [[ ! ( -s ${altmovfile} ) ]]; then
      echo "*** File ${altmovfile} is missing, unreadable, or empty" 1>&2
      altmovfile="missing.png"
    fi
    echo "  alternate movie file = ${altmovfile}"  1>&2

    # Create alternate movie button:
    if [[ "${altmovfile}" != "missing.png" ]]; then
      altmovbutt='[<a href="'"${altmovfile}"'">'"${alttxt}"'</a>]'
    else
      altmovbutt="[×]"
    fi
  fi

  # Format the movie icon
  iconbutt='<a href="'"${movfile}"'"><img src="'"${moviconfile}"'"></a>'
  
  # echo "${frabutt} ${strbutt} ${movbutt} ${altmovbutt} ${iconbutt}"  1>&2
  
  # Output the entry
  if [[ ${n} -eq 0 ]]; then
    echo "    <tr valign=top>" >> ${htmfile}
  fi
  cat <<EOF >> ${htmfile}
    <td nowrap>${iconbutt}<br><font size=+2><b>${ra}</b></font><br>&nbsp;</td>
    <td nowrap><small>${frabutt}&nbsp;&nbsp;<br>${strbutt}&nbsp;&nbsp;<br>${movbutt}&nbsp;&nbsp;<br>${altmovbutt}&nbsp;&nbsp;<br>${povbutt}&nbsp;&nbsp;</small></td>
EOF
  n=$(( ${n} + 1 ))
  if [[ ${n} -ge ${iconsperrow} ]]; then
    echo "    </tr>" >> ${htmfile}
    n=0
  fi
done

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

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