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

CLOUDSDIR=/var/lib/xplanet
CLOUDSFILE=clouds_1600.jpg
CLOUDSLOCATION=http://xplanet.sourceforge.net
CLOUDSCURRENT=clouds_current.jpg
# PROXYSTRING="--proxy=off"
# PROXYSTRING="-p 'http_proxy=http://wittenau.ivbb.bund.de:80/'"
PROXYSTRING=""
export http_proxy=http://wittenau.ivbb.bund.de:80/

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

DAYSTOSTORE=10

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
# wget -q $PROXYSTRING $CLOUDSLOCATION/$CLOUDSFILE

lwp-request -H 'Pragma: no-cache' $PROXYSTRING $CLOUDSLOCATION/$CLOUDSFILE > clouds_1600.jpg

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
       lwp-request -H 'Pragma: no-cache' $PROXYSTRING $CLOUDSLOCATION/$CLOUDSFILE > clouds_1600.jpg
#       wget -q $PROXYSTRING $CLOUDSLOCATION/$CLOUDSFILE
       CMP=`cmp $CLOUDSFILE $CLOUDSDIR/$CLOUDSCURRENT`
       if [ -n "$CMP" ] ; then
         break
       fi
       i=$((i-1))
     done
     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
rm -f $CLOUDSDIR/$CLOUDSCURRENT
ln -s clouds_${DATE}.jpg $CLOUDSDIR/$CLOUDSCURRENT

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