#!/bin/sh
## Obtain clouds images for xplanet and store them in /var/lib/xplanet

# set proxy
if [ -e /etc/local/profile.local ] ; then
   . /etc/local/profile.local > /dev/null
fi

CLOUDSDIR=/var/lib/xplanet
CLOUDSFILE=clouds_2048.jpg

## Andere interessante Marker (Vulkane, Erdbeben, Stürme)
## http://www.wizabit.eclipse.co.uk/xplanet

CLOUDSCURRENT=clouds_current.jpg
BINDOWNLOAD="/usr/bin/download_clouds.pl"

# in case of not updated clouds file sleep some time
TIMETOSLEEP=20
# and try fetching again NUMTRY times
NUMTRY=3

DAYSTOSTORE=5

DATE=`date +%Y%m%d%H`
if [ ! -d $CLOUDSDIR ] ; then
  mkdir -p $CLOUDSDIR || exit -1
fi
unset DISPLAY
cd $CLOUDSDIR
# just delete a possibly exiting clouds file to avoid wget from
# renaming the new one
rm -f $CLOUDFILE

cd /tmp
$BINDOWNLOAD > /dev/null
mv clouds.jpg $CLOUDSFILE

if [ -L $CLOUDSDIR/$CLOUDSCURRENT ] ; then
  CMP=`cmp $CLOUDSFILE $CLOUDSDIR/$CLOUDSCURRENT`
  if [ -z "$CMP" ] ; then
     echo clouds are equal
     i=$NUMTRY
     while [ $i -gt 0 ] ; do 
       sleep $TIMETOSLEEP

       $BINDOWNLOAD > /dev/null
       mv clouds.jpg $CLOUDSFILE

       CMP=`cmp $CLOUDSFILE $CLOUDSDIR/$CLOUDSCURRENT`
       if [ -n "$CMP" ] ; then
         break
       fi
       i=$((i-1))
     done
     # User xplanet darf nicht /var/log/messages schreiben ... und so dolle wichtig ist's ja auch nicht
     # echo `date +"%b %e %H:%M:%S"` `hostname` `basename $0`: Unable to obtain new clouds file >> /var/log/messages
     exit 0
  fi
fi
mv $CLOUDSFILE $CLOUDSDIR/clouds_${DATE}.jpg
# chown tillea: $CLOUDSDIR/clouds_${DATE}.jpg
rm -f $CLOUDSDIR/$CLOUDSCURRENT
ln -s clouds_${DATE}.jpg $CLOUDSDIR/$CLOUDSCURRENT
# chown tillea: $CLOUDSDIR/$CLOUDSCURRENT

### löschen älterer Wolkenbilder
find $CLOUDSDIR -maxdepth 1 -mtime +${DAYSTOSTORE} -name "*.jpg" -exec rm \{\} \;
