#!/bin/bash

url="http://unappel.ch/public/091017-support-numbers/code/current.zip"

greet="`perl -e 'print qw(hello)' 2>/dev/null`"

if [ "$greet" != "hello" ]
then
  echo "[$0] Maybe Perl is not installed?"
  exit
else
  echo "[$0] Perl is installed"
fi

dir=`echo "$0" | perl -ne 's/\/[^\/]*$//; print'`

cd "$dir"

if [ "`pwd`" = "$dir" ]
then
  echo "[$0]" working folder found
else
  echo "[$0]" not in working folder
  exit
fi

if [ -f `basename "$0"` ]
then
  echo "[$0] working in a right folder"
else
  echo "[$0] bad working folder"
  exit
fi

if [ -f current.zip ]
then
  echo "[$0] removing the previous version"
  rm current.zip
else
  echo "[$0] no previous version"
fi

if [ -f current.zip ]
then
  echo "[$0]" cannot remove the old package
  exit
fi

/usr/bin/wget $url

if [ -f current.zip ]
then
  echo "[$0]" script is downloaded
else
  echo "[$0]" script is not downloaded
  exit
fi

if [ -d code ]
then
  echo "[$0]" deleting the old script folder
  rm -r code
fi

if [ -d code ]
then
  echo "[$0]" cannot delete the old script folder
  exit
fi

mkdir code 

if [ -d code ]
then
  echo "[$0] code folder is created" 
else
  echo "[$0] cannot access script folder"
  exit
fi

/usr/bin/unzip current.zip -d code

if [ -f code/run.pl ]
then
  echo "[$0]" perl script is extracted
else
  echo "[$0]" cannot extract the perl script
  exit
fi

if [ "$1" = "support" ]
then
  echo "[$0] stat for only outgoing support emails"
else if [ "$1" = "oper" ]
then
  echo "[$0] stat for all operation emails"
else
  echo "[$0] bad argument"
  exit
fi; fi

date >> std.log
date >> err.log

cd code
/usr/bin/perl run.pl $1 >> ../std.log 2>> ../err.log
cd ..

tail -5000 std.log > last.std.log
rm std.log
mv last.std.log std.log

tail -5000 err.log > last.err.log
rm err.log
mv last.err.log err.log

date >> std.log
date >> err.log

echo "[$0]" end of reporting


