#!/bin/ksh
#
#-------------------------------------------------------------------
# Function: monitorsend logtype
#
#
# Purpose: send any *.txt capture or extract logs in the monitor 
# directory to the remote host and optionally e-mail them to the 
# monitor.
#
# It is necessary to copy the files to the remote system onto
# a disk that is known to the email_notification program.
#
# This is a separate function that can be run in the background
# after the monitorcopy script has been called in the foreground
# to set up all the files of appropriate log name for transfer.
# This should also transfer any files of the input logtype that 
# failed to transfer previously.
#
#-------------------------------------------------------------------
#===================================================================
# C H A N G E   L O G
#
# KLP		10/31/06	created
# KLP   01/12/07  ssh, scp; no mail
# BCW		12/17/08	Abstracted embeded setttings

#===================================================================
#
logtype=${1:-extract}
#
#-------------------------------------------------------------------
# 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 [[ ${#monitorEmail} -eq 0 ]]; then
	monitorEmail=maldjian@wfubmc.edu
fi

if [[ ${#monitorRemoteDir} -eq 0 ]]; then
	billRemoteDir=/ansir2/mojoe_monitor
fi

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

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

#monitorLocalDir=/export/home/sdc/mojoe/log/monitorlog
monitorLocalDir=$mojoe_dir/log/monitorlog


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 $monitorRemoteDir 2>/dev/null`
if (test ${#reply} -lt 1) then
    return
fi
#
cwd=$PWD
cd $monitorLocalDir
logs=`ls -1 *$logtype*.txt 2>/dev/null`
for fname in $logs
do
    if (test -f $fname && test -s $fname) then
        subjectline=`echo $HOSTNAME'_monitor_'$logtype`
        scp -p $fname $sshuser@$sshserver:$monitorRemoteDir/$fname2 2>/dev/null
        if (test $mailLog -eq 1) then
            ssh -n -l $sshuser $sshserver $fmri_dir/email_notification $monitorRemoteDir/$fname $subjectline $monitorEmail 2>/dev/null
        fi
        if (test $keepLog -eq 0) then
            ssh -n -l $sshuser $sshserver rm -rf $monitorDir/$fname 2>/dev/null
        fi
        rm -f $fname
        echo ... $monitorRemoteDir/$fname >> monitor.log
    fi
done
cd $cwd
