#!/bin/ksh
# @(#)95        3.1  sendto.sh   Jan 10 2006

VERSION="3.1"

#
# COMPONENT_NAME: SENDTO/GETFROM
#
# FUNCTIONS:
#
# ORIGINS:
#  10-22-90 - IHS/MFD original script to use uucp only.
#  10-31-91 - IHS/MFD changed -n option to -i cause echo command has its
#                     own -n option under version V release 3 of unix
#   7-6-92  - IHS/MFD added SMAIL variable to either send or not send mail
#             to user and root on remote about the transfer
#             if 'env SMAIL=no' precedes the sendto call, no mail will be sent
#   9-17-92 - IHS/RAW modified script to use the 'getopt' command and took
#             out the recursive calls.
#   4-7-94  - IHS/MFD added -c for compress file option
#
#   8-1-94  - IHS/MFD ftpsend/ftpget
#  12-1-94  - IHS/MFD added background and mail capabilities
#             This command now defaults to sending and getting in the
#             background. To send/get in the foreground use the -x or -v option.
#             This script now calls /usr/bin/ftpsend1.
#
#   4-15-95 - IHS/RAW merged sendto, getfrom, and ftpsend/ftpget functions
#             a single script.
#   8-28-95 - IHS/MFD changed at command to run under SCO
#   9-13-95 - IHS/MFD changed to allow "*" wildcard in filename arguments
#  10-30-95 - IHS/MFD if you have gzip use it to compress with on large files
#   8-28-96 - IHS/RAW Added copylocal toggle to FTP to allow copying of files
#             on same system.
#   1-10-97 - IHS/MFD changed setting of transfer mode (binary) to work with NT
#   2-18-1999 -IHS/MFD changed -n option to stop compression regardless of size
#   8-31-05 - CNI/CLB Added -u flag to toggle sunique/runique option
#   9-23-05 - IHS/RAW Stripped all references to the uucp utility.
#                     Added versioning to be displayed.
#   1-10-06 - IHS/REP Changed the check to ensure the systemid is a valid
#                     system id from ping to nslookup as pings are prohibited
#                     at many sites.  
#   
#
# FILE NAME: sendto
#
# FILE DESCRIPTION: High-level KORN shell script to send/get file(s)
#   to/from site(s) via ftp.
#
#   Install sendto into the /usr/bin directory and link to getfrom:
#     install -o sendto
#     ln -f /usr/bin/sendto /usr/bin/getfrom
#
#   Basic functions performed are:
#     1)  transmit file(s) to site(s) that are on the IHS network via
#         FTP.
#     2)  receive file(s) from site(s) that are on the IHS network via
#         FTP.
#
#     See Usage message for explanation of parms
#
#
# RETURN VALUE DESCRIPTION:
#                             0         Successful
#                             non-zero  Unsuccessful
#
# EXTERNAL PROCEDURES CALLED: (other than standard utilities)
#       ftp - The -n is used to avoid clashing with .netrc files.
#             The -i to avoid interactive prompting with multiple files.
#             The -v to get a dialog of the ftp session and hence its
#             results.
#             By default, files are grabbed from the anonymous ftp pub
#             directory remotely and placed in the anonymous ftp pub
#             directory locally.
#      gzip - The -v is used for verbose mode.
#             The -9 is used to compress better.
#  compress - The -f is used to Force compression of the file
#             The -v is used write the percentage of compression
#        at - now + 1 minute is used as the time to run the ftp job.
#             The -m is used to mail a message to the user about the
#             successful execution
#
# GLOBAL VARIABLES:
#   DEBUG - Set DEBUG to true and export to invoke debug mode for the
#           script. (ex. export DEBUG=true )
#    RDIR - The Remote DIR variable can be set prior to call to use
#           other than the default directories.
#    LDIR - The Local DIR variable can be set prior to call to use
#           other than the default directories.
#    Note:  The remote directory must always be either the ftp pub
#           directory or one of its subdirectories.
#

# Ensure that Korn SHell is the executing shell
[ "${RANDOM}" = "${RANDOM}" ] && exec /bin/ksh -c "${0}" ${@+"${@}"}

# Debug mode is activated
if [ "${DEBUG}" = "true" ]
then
  unset DEBUG
  exec /bin/ksh -x "${0}" -d ${@+"${@}"}
fi

################################# USAGE #######################################
#
# NAME: USAGE()
#
# DESCRIPTION: Issue "usage" message and exit.
#
# INPUT:
#        None
#
# OUTPUT:
#        Error messages (Standard Error)
#
# RETURN VALUE DESCRIPTION:
#                           2
#
# NOTE: This function will not return (i.e., it will exit the entire
#       script with exit status of 2).

USAGE () {
  sendtohelp () {
    print - "\t-i = invoke immediately, no queueing (verbose mode for ftp)"
    if [ -x /usr/bin/gzip ]
    then
      print - "\t-g = compress file with 'gzip' before sending"
    else
      print - "\t-c = compress file with 'compress' before sending"
    fi
    print - "\t-n = suppress compression of file(s) regardless of size"
    print - "\t     By default any file => 2MBs will be compressed first"
    print - "\t-f systemid_file = use systemid_file to specify sites"
    print - "\nFTP Options:"
    print - "\t-a = invoke ascii mode (default is binary)"
    print - "\t-l user:password = use user:password as ftp login"
    print - "\t-r remote_dir = use remote subdirectory to send the file into"
    print - "\t-u = to turn OFF copy unique (sunique)"
    print - "\nExample:"
    print - "\tTo send files to cmbsyb without queueing and compress the"
    print - "\tfiles with the 'gzip' utility:"
    print - "\t\tsendto -ig cmbsyb file1 file2"
  }

  getfromhelp () {
    print - "\t-i = invoke immediately, no queueing (verbose mode for ftp)"
    print - "\t-f systemid_file = use systemid_file to specify sites"
    print - "\nFTP Options:"
    print - "\t-a = invoke ascii mode (default is binary)"
    print - "\t-l user:password = use user:password as ftp login"
    print - "\t-r remote_dir = use remote subdirectory to get the file from"
    print - "\t-u = to turn OFF copy unique (runique)"
    print - "\nExample:"
    print - "\tTo retrieve files from cmbsyb PATCHES directory without queueing:"
    print - "\t\tgetfrom -i -rPATCHES cmbsyb patchfile1 patchfile2"
  }

  print - "USAGE:  ${PROG} [ options ] systemid file1 [file2] ... [fileN]"
  print - "\t${PROG} [ options ] -f systemid_file file1 [file2] ... [fileN]"
  print - "\nGeneral Options:"
  case ${PROG} in
    sendto)   sendtohelp ;;
    getfrom)  getfromhelp ;;
  esac
  exit 2
}

############################## main ############################################

PROG=$(basename $0)                # Capture name of PROGram
print - "\n\t${PROG}: Version ${VERSION}\n"
case ${PROG} in                    # Set the appropriate options for
    sendto)   OPTARGS="acdinuf:l:r:"   # parsing by getopts.
              [ -x /usr/bin/gzip ] && OPTARGS="adginuf:l:r:"
              ;;
    getfrom)  OPTARGS="adiuf:l:r:" ;;
esac
MINARG=2                           # MINimum ARGuments default
FTPRDIR=pub                        # FTP default remote and local directories
NOPACK=false			   # default is to allow compression
COPYUNIQUE=true			   #CNI/CLB/8-31# default is unique xfers

# Parse command flags and arguments
set -- $(getopt ${OPTARGS} $*)
[ $? -ne 0 ] && USAGE
for ARG in $*
do
  case ${ARG} in
    -a)  FTYPE=as                  # Change to ebcdic mode for ftp
         shift
         ;;
    -c)  PACK="compress -fv"
         EXT=Z
         shift
         ;;
    -d)  FTPCOMMAND="ftp -dniv"
         shift
         ;;
    -g)  PACK="gzip -9v"
         EXT=gz
         shift
         ;;
    -i)  FTPQUEUE="/bin/ksh"        # Set to 'ksh' so the ftp script can
         shift                      # be executed in verbose mode
         ;;
    -n)  NOPACK=true              #unset UUMAIL    # Disable UUcp MAIL messaging
         shift
         ;;
    -f)  shift
         SYSFIL=$1                 # A system id file is going to be used
         MINARG=1                  # Reset MINimum ARGuments
         shift
         ;;
    -l)  shift
         FTPUSER=${1%%:*}         # Parse out login name
         PASS=${1##*:}            # Parse out password
         LDIR=${LDIR:-${HOME}}
         [ "${FTPRDIR}" = pub ] && unset FTPRDIR
         shift
         ;;
    -r)  shift                    # Check if '/' is first character
         RDIR=/${1#/}
         FTPRDIR=pub${RDIR}     # Insert directory name to '/'
         shift                    # A '/' precedes directory name
         ;;
    -u)	 COPYUNIQUE=false          #CNI/CLB/8-31#
         shift			   # Set to turn off copy unique 
         ;;
    --)  shift; break;;
  esac
done

#  check for MINinmum ARGuments
[ $# -lt ${MINARG} ] && USAGE

####################  DEFAULTS  ##############################################
#
# These variables are set to the defaults if not set in the parsing
# of the options.

FTPUSER=${FTPUSER:-anonymous}           # Default anonymous ftp login name
PASS=${PASS:-"${LOGNAME}@$(hostname)"} # Default anonymous ftp password
FTYPE=${FTYPE:-bi}                # Ftp in binary mode
FTPQUEUE=${FTPQUEUE:-"at now + 1 minute"} # Use at to execute ftp script
UUCPDIR=/usr/lib/uucp             # UUCP home directory
                                  # FTP default local directory
FTPLDIR=${LDIR:-$(awk -F: '/^anonymou:/ {print $6}' /etc/passwd)/pub}

# Check to ensure Systemid is a valid file.
if [ -n "${SYSFIL}" ]
then
  if [ -r ${UUCPDIR}/${SYSFIL} ]
  then
    SYSTEMS=$(cat ${UUCPDIR}/${SYSFIL})
  elif [ -r ${SYSFIL} ]
  then
    SYSTEMS=$(cat ${SYSFIL})
  else
    print - "${PROG}: Systemid file '${SYSFIL}' not found"
    exit 1
  fi
else
  SYSTEMS=$1
  shift
fi

unset FILES
(( FILKNT = 0 ))
for FIL in $*
do
  # Check to ensure each argument is a file and is > 0 length
  if [ ${PROG} = sendto ]
  then
    if [ ! -s ${FIL} ]
    then
      print - "${PROG}: '${FIL}' file not found or it is zero length"
      continue
    fi
    if [ $(ls -s ${FIL} | awk '{print $1}') -ge 2048 ] &&\
       [ ${FIL##*.} != z -a ${FIL##*.} != Z -a ${FIL##*.} != gz ] &&\
       [ ${NOPACK} = false ]
    then                          # If file needs to be compressed
      if [ -x /usr/bin/gzip ]     # use gzip if you have it
      then
      PACKCOMM=${PACK:-"gzip -9v"}
      FILEXT=${EXT:-gz}
      else
      PACKCOMM=${PACK:-"compress -fv"}
      FILEXT=${EXT:-Z}
      fi
      if ${PACKCOMM} ${FIL}           # then execute the compression command
      then
        FIL=${FIL}.${FILEXT}
      else
        print - "${PROG}: Error in packing ${FIL} file"
        continue
      fi
      unset PACKCOMM FILEXT
    fi
  fi
  FILES[${FILKNT}]=${FIL}
  (( FILKNT = FILKNT + 1 ))
done

if [ ${#FILES[*]} -gt 0 ]
then
  for SYS in ${SYSTEMS}
  do
    # Check to ensure the systemid is a valid system id
    unset COMMAND
    if nslookup ${SYS} > /dev/null 2>&1
    then
      COMMAND=${FTPCOMMAND:-"ftp -niv"}
      case ${PROG} in
        sendto) FILECOM=put ;;
        getfrom) FILECOM=get ;;
      esac
      if [ ${FILKNT} -gt 1 ] || print "$*" | grep '*' > /dev/null 2>&1
      then
        FILECOM=m${FILECOM}
      fi
    else
      print - "${PROG}: '${SYS}' system not listed in the Systems table."
      print - "         -or- system is outside IHSNET Firewall."
      continue
    fi
    # Processing to be done via FTP
    LSYS=$(hostname)
    [ "${FTPQUEUE%% *}" = "at" ] && print - "${SYS} \c"
    {
    print - "print - \"Attempting ftp connection to ${SYS}\""
    print - "${COMMAND} ${SYS} <<EndFTP"
    [ ${SYS} = "${LSYS%%.*}" -a -n "$(uname -a | grep AIX)" ] && print "\tcopylocal"
    print - "\tuser ${FTPUSER} ${PASS}"
    print - "\t${FTYPE}"      #IHS/MFD dropped 3 lines to work with NT
    if [ "${COPYUNIQUE}" = "true" ]    #CNI/CLB/8-31#
    then
      case ${PROG} in
        sendto)   print - "sunique" ;;
        getfrom)  print - "lcd ${FTPLDIR}"
                  print - "runique"
                  ;;
      esac
    fi
    [ -n "${FTPRDIR}" ] && print - "\tcd ${FTPRDIR}"
    for FIL in ${FILES[*]}
    do
      if [ $(dirname ${FIL}) != "." ]
      then
        [ ${PROG} = sendto ] && p