#!/bin/ksh
#
#-------------------------------------------------------------------
# Function: billsend
#
#
# Purpose: send any mojoe_*.txt logs in the log/billing 
# directory to the remote host and optionally e-mail them to the 
# biller.
#
# It is necessary to copy the files to the remote system onto
# a disk that is known to the email_notification program.
#
# This function can be run in the background.
#
#-------------------------------------------------------------------
#===================================================================
# C H A N G E   L O G
#
#===================================================================
# BCW		12/17/08	 Abstracted embeded setttings
#
#-------------------------------------------------------------------
# BEGIN ... VARIABLE SETTINGS
#

#check for settings in current directory, then possibly one directory down.
if [[ -e settings.ksh ]]; then
. ./settings.ksh
elif [[-e ../settings.ksh ]]; then
. ../settings.ksh
fi

#----
#Check default settings
#----
mojoe_dir=$MOJOE_DIR
if (test ${#mojoe_dir} -lt 1)
    then
    mojoe_dir=$HOME/mojoe
fi

if [[ ${#billEmail} -eq 0 ]]; then
	billEmail=maldjian@wfubmc.edu
fi
if [[ ${#billRemoteDir} -eq 0 ]]; then
	billRemoteDir=/ansir2/mojoe_bill
fi

if [[ ${#sshserver} -eq 0 ]]; then
	sshserver=152.11.158.50
fi

if [[ ${#sshuser} -eq 0 ]]; then
	sshuser=fmri
fi
#echo "Billsend: $sshuser:$sshserver"
#---
#End check default settings
#---

#billLocalDir=/export/home/sdc/mojoe/log/billing
billLocalDir=$mojoe_dir/log/billing

mailLog=0
keepLog=1
#
# END ..... VARIABLE SETTINGS
#-------------------------------------------------------------------
#
if (test $mailLog -eq 0 && test $keepLog -eq 0) then
    return
fi
reply=`ssh -n -l $sshuser $sshserver ls -lsdt $billRemoteDir 2>/dev/null`
if (test ${#reply} -lt 1) then
    return
fi
#
cwd=$PWD
cd $billLocalDir
logs=`ls -1 mojoe_*.txt 2>/dev/null`
for fname in $logs
do
    if (test -f $fname && test -s $fname) then
        subjectline=`echo $HOSTNAME"_"mojoe_bill`
        scp -p $fname $sshuser@$sshserver:$billRemoteDir/$fname2 2>/dev/null
        if (test $mailLog -eq 1) then
            ssh -n -l $sshuser $sshserver $fmri_dir/email_notification $billRemoteDir/$fname $subjectline $billEmail 2>/dev/null
        fi
        if (test $keepLog -eq 0) then
            ssh -n -l $sshuser $sshserver rm -rf $billDir/$fname 2>/dev/null
        fi
        rm -f $fname
        echo ... $billRemoteDir/$fname >> bills.log
    fi
done
cd $cwd
