#!/bin/bash

cd /usr/callbook

#export day=`date +%a | tr '[A-Z]' '[a-z]'`
export day=`cat nextday`
export dayset=0
export ftp=1
export mail=1


if let "$# > 0"
then
	dayset=1
	day=$1
fi
if let "$# > 1"
then
	ftp=0
fi
if let "$# > 2"
then
	mail=0
fi

echo Daily update for $day

#
# First, retrieve the daily zip file
#

if [ $ftp -eq 1 ]
then
	echo Retriving via FTP.....
	/usr/callbook/ftp-fcc-data $day
fi

#
# backup the current appl.dat and indiv.dat files
#

mv -f appl.dat appl.dat.bak
mv -f indiv.dat indiv.dat.bak

#
# Now, unzip the file
#

echo -e "\nUnziping file - wait...\n"
/usr/local/bin/unzip -L -o $day appl.dat indiv.dat

#
# And remove the zip file, since we're done with it
#

/bin/rm $day.zip

#
# Now update from the appl.dat file
#

if [ -s appl.dat ]
then
	# The next line (or an equiv. one) must be there, since GDBM
	# won't allow us to update if there are reader applications active
	killall callbook

	echo -e "\nUpdating from appl.dat file....\n"
	/usr/callbook/convert_appl
else
	echo -e "\nSkipping zero length appl.dat file....\n"
fi

#
# Now update from the indiv.dat file
#

if [ -s indiv.dat ]
then
        # The next line (or an equiv. one) must be there, since GDBM
        # won't allow us to update if there are reader applications active
        killall callbook

	echo -e "\nUpdating from indiv.dat file....\n"
	/usr/callbook/convert_indiv
else
	echo -e "\nSkipping zero length indiv.dat file....\n"
fi


#
# Now disable the mailings if both files were zero length
#

if [ ! -s appl.dat ]
then
  if [ ! -s indiv.dat ]
  then
	mail=0
	mv -f appl.dat.bak appl.dat
	mv -f indiv.dat.bak indiv.dat
  fi
fi


#
# Now calculate the next day name, if not executed manually
#

if [ $dayset -ne 1 ]
then
	if [ $day = "mon" ]
	then
		day="tue"
	elif [ $day = "tue" ]
	then
		day="wed"
	elif [ $day = "wed" ]
	then
		day="thu"
	elif [ $day = "thu" ]
	then
		day="fri"
	elif [ $day = "fri" ]
	then
		day="sat"
	elif [ $day = "sat" ]
	then
		day="mon"
	fi
	echo -n $day >nextday
fi

