#!/bin/sh

export PATH=/bin:/usr/bin

PICTURE=http://weather.met.ed.ac.uk/jpg/image.jpg
#WEATHER=/disk/home/xweb/weather
#WEATHER=/opt/x_apache/weather
WEATHER=/opt/x_apache/weather/public_html/cam
BASEURL=http://xweb.geos.ed.ac.uk/weather/cam
INPLACE=weather.js
TMPFILE=weather.tmp

WGET=$(which wget)

weather_collect () {
   cd $WEATHER

   NOW=`date +%Y%j%H%M%S`.jpg
   /usr/bin/wget 2>/dev/null -O $NOW $PICTURE
   if [ ! -s $NOW ] ; then
      rm -f $NOW
   else
      # Add a "latest" image link to the most recent image
      ln -s $NOW newest.jpg
      mv newest.jpg latest.jpg
   fi
   
   # loop twice so we can produce 
   # more recent pictures

   ( for i in 20 40; do
        sleep 20
        NOW=`date +%Y%j%H%M%S`.jpg
        /usr/bin/wget 2>/dev/null -O $NOW $PICTURE
        if [ ! -s $NOW ] ; then
           rm -f $NOW
        fi
     done
   ) &
}

weather_archive () {
   cd $WEATHER
#  Move items more than 40 mins old to archive
   RMLIST=`find .  -maxdepth 1 -mmin +39 -name \[0-9\]*.jpg`
   if [ "$RMLIST" != "" ] ; then
      [ -d archive ] || mkdir archive
      mv $RMLIST archive
   fi

   # Remove items more than 7 days old from archive
   RMLIST=`find archive -mtime +7 -name \[0-9\]*.jpg`
   RMLIST=`find archive -mmin +1440 -name \[0-9\]*.jpg`
   if [ "$RMLIST" != "" ] ; then
      rm $RMLIST
   fi
}

weather_animate () {
   cd $WEATHER

   cat >$TMPFILE <<EOJS
var counter = 1
var timer
var speed = 200
var numpics

/* load the numpics images into an array of images */

var imgs = new Array(numpics)
i = 1
EOJS

   for image in `ls [0-9]*.jpg`
   do
      echo "imgs[i] = new Image(); imgs[i].src = '$BASEURL/$image'; ++i" >>$TMPFILE
   done

   cat >>$TMPFILE <<EOJS
numpics = i
   
function animate() {
/* As long as the counter is less than numpics add 1 else make the counter 1*/
        s = speed
        counter += 1
        if (counter == numpics - 1){
                s = speed * 5 + 100
        }
        if (counter >= numpics){
                counter = 1
        }
        document.anim.src = imgs[counter].src
        timer=setTimeout("animate()", s)
}

function faster() {
   speed -= 100
   if (speed <= 0) { speed = 1 }
}

function slower() {
   speed += 100
}
EOJS

mv $TMPFILE $INPLACE
}

archive_index () {
   cd $WEATHER/archive

   cat <<EOHTML >$TMPFILE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
   <TITLE>Animated Skyscape</TITLE>
</HEAD>
<BODY>
<p>
EOHTML

   for file in [0-9]*.jpg
   do
      echo "<a href=$BASEURL/archive/$file>$file</a> " >>$TMPFILE
   done

   cat <<EOHTML >>$TMPFILE
</p>
</BODY>
</HTML>
EOHTML

   mv $TMPFILE index.html
}

if [ "$1" != "" ] ; then
   WEATHER=$WEATHER/$1
   BASEURL=$BASEURL/$1
   weather_animate
else
   weather_collect
   weather_archive
   weather_animate
   archive_index
fi

