#!/bin/sh
#==========
# CHS to FI data transmission
#==========
if [ "$1" = "" ] ; then
  echo "usage: chsftpepo_fi <password> <filename_root>"
  exit -1
fi
if [ "$2" = "" ] ; then
  echo "usage: chsftpepo_fi <password> <filename_root>"
  exit -1
fi
cd /usr/spool/chsdata
#==========
# Extract the data from the password file
#==========
PWDF=password_fi
HNAME=`hostname | cut -d . -f 1`
if [ "$3" = "" ] ; then
  # remove all but this systems line from the password file
  cat $PWDF | grep $HNAME > chs_temp
  mv chs_temp $PWDF
else
  # fool the script into working as another location
  HNAME=$3
  PWDF=../$PWDF
  if ! [ -e $HNAME ] ; then mkdir $HNAME ; fi
  cd $HNAME
fi
# Make sure the xmitted sub director exists
if ! [ -e xmitted ] ; then
  mkdir xmitted
  chmod ugo+rwx xmitted
fi
LINE=`grep $HNAME $PWDF`
LOGINNAME=`echo $LINE | cut -d : -f 2` ; LOGINNAME=`crypt $1 $LOGINNAME`
PWORD=`echo $LINE | cut -d : -f 3` ; PWORD=`crypt $1 $PWORD`
TNAME=`echo $LINE | cut -d : -f 4`
echo "Sending files as: $HNAME"
echo "----- "`date`" -----" >> chsepo_fi.log
#==========
# For each file waiting to be sent do the following
#==========
if [ "`ls $2*`" = "" ] ; then
  echo "No files to send !"
  exit 0
fi
for fn in `ls $2*` ; do
#==========
# Convert the two 80 character DHR records into one 140 character DHR record
#==========
TXFILE=converted.txt
grep -v -e "^/" $fn > $TXFILE
#==========
# Now lets go and send this file via FTP
#==========
LOGFILE=put_log.`date +"%j"`
FNAME=\'IHS.A`echo $LOGINNAME | cut -d s -f 2`."EPO(+1)"\'
echo "Sending file: $fn[$TXFILE] to $FNAME"
ftp -nv <<EOF > $LOGFILE 2>&1
  open $TNAME
  user $LOGINNAME $PWORD
  quote SITE RECFM=FB LRECL=80 BLKSIZE=0
  put $TXFILE $FNAME
  quit
EOF
echo "Done !"
cat $LOGFILE >> chsepo_fi.log
#==========
# Does the file appear to have been sent
#==========
if [ "`grep -e "^250" $LOGFILE`" != "" ] ; then
  echo "The file: $fn has successfully been sent as $FNAME"
  mv $fn xmitted/$fn
else
  echo "Send failed ..... sorry!"
fi
# Cleanup the temporary files
rm $TXFILE $LOGFILE
done ; # go back and send the next file
