#-------------------------------------------------------------------------------
# Run any file containing DB2 queries or commands; send output to a date headed file.
# It's up to the caller to establish a database connection, e.g. by a call to CONNECT()
#
# Arguments: $1 the input filename and full path. Must use semi-colon delimiters.
#            $2 command line options, e.g. -tvf "+c -txf" etc.
#            $3 maximum acceptable return code from running $1 
#            $4 full qualified path and file name for results. NONE for no output.
#            $5 compress (gzip) $3 option  - supply either compress or nocompress
#            $6 ksh debug option - either +x or -x.
RUN_DB2FILE()
{
 if [[ $# -eq 6 ]]
 then
    DEBUG=$6 ; set "$DEBUG"
    INPUT_FILE=$1
    typeset -l CL_OPTIONS=$2
    MAX_RETURN_CODE=$3 
    OUTPUT_FILE=$4
    COMPRESS_OPTION=$5
    if [[ "$OUTPUT_FILE" == "NONE" ]]
    then 
         :
    else INIT_OUTPUT_FILE $OUTPUT_FILE $DEBUG  
         print "\nCommand to run:"         >> "$OUTPUT_FILE" 
         print "  db2 +o $CL_OPTIONS $INPUT_FILE -z $OUTPUT_FILE \n" >> "$OUTPUT_FILE"
    fi
 else
    MESSAGE "$0 RUN_DB2FILE() Bad call! \n " PLAIN E +x
    MESSAGE "Usage: RUN_DB2FILE \$1 input file and path \$2 DB2 command line options \$3 maximum acceptable return code \$4 output file and path \$5 compress|nocompress \$6 ksh debug switch +x|-x" PLAIN E +x  
    return 1
 fi 

 EXISTENCE_TEST $INPUT_FILE $DEBUG

 if [[ "$OUTPUT_FILE" == "NONE" ]]
 then
    db2 -o $CL_OPTIONS $INPUT_FILE   
    RETURN_CODE=$?
 else 
    db2 +o $CL_OPTIONS $INPUT_FILE -z $OUTPUT_FILE
    RETURN_CODE=$?
 fi
 if [[ $RETURN_CODE -gt $MAX_RETURN_CODE ]]; then
    MESSAGE "RUN_DB2FILE() return code: \"${RETURN_CODE}\" " PLAIN E $DEBUG
    if [[ "$OUTPUT_FILE" == "NONE" ]]; then
       MESSAGE "View log file for further details" PLAIN E $DEBUG
    else
       MESSAGE "View: \"${OUTPUT_FILE}\" for further details" PLAIN E $DEBUG
    fi 
    return $RETURN_CODE
 else
    case  $COMPRESS_OPTION in
          compress|COMPRESS)
             ZIP_IT $OUTPUT_FILE $DEBUG_SWITCH  
             print "Output saved to: \"${OUTPUT_FILE}.gz\""
             ;;
          *)
             if [[ "$OUTPUT_FILE" == "NONE" ]]
             then
                print "Output saved to log file."
             else 
                print "Output saved to: \"${OUTPUT_FILE}\""
             fi
             ;;
    esac
 fi
}
