#-------------------------------------------------------------------------------
# Run any CLP command and write the output to a date headed file.
# It's up to the caller to establish a database connection if it's needed,  e.g. by a call to CONNECT()
# Some CLP commands require an instance attachment.

# Arguments: $1 the DB2 command string in quotes.
#            $2 maximum acceptable return code from running $1
#            $3 full qualified path and file name for results. NONE for no output.
#            $4 compression (gzip): compress or nocompress|any string for $3 output.
#            $5 instance attachment: either "attach" or any string to bypass attachment.
#            $6 ksh debug: either +x or -x.
# Example: to run db2 get dbm cfg show detail, stop on any error, and save compressed 
#          output to the instance home directory as dbmcfg.out.gz without any debugging:
# RUN_DB2CLP "get dbm cfg show detail" 0 $INSTHOME/dbmcfg.out nocompress attach +x

RUN_DB2CLP()
{
 if [[ $# -eq 6 ]]
 then
    DEBUG=$6 ; set "$DEBUG"
    DB2_COMMAND=$1
    MAX_RETURN_CODE=$2 
    OUTPUT_FILE=$3
    COMPRESS_OPTION=$4
    typeset -u ATTACH_OPTION=$5 
    if [[ $OUTPUT_FILE == "NONE" ]]
    then :
    else INIT_OUTPUT_FILE $OUTPUT_FILE $DEBUG  
         print "\nCommand run:"         >> "$OUTPUT_FILE" 
         print "  db2 ${DB2_COMMAND}\n" >> "$OUTPUT_FILE"
    fi
 else
    MESSAGE "$0 RUN_DB2CLP() Bad call! " PLAIN E +x
    MESSAGE "$0 RUN_DB2CLP() Usage: \$1 DB2 command string in quotes \n \$2 maximum acceptable return code \n \$3 output path and file or NONE \n \$4 compress|nocompress \n \$5 attach|noattach \n \$6 ksh debug either +x or -x" PLAIN I +x 
    return 1
 fi 

 if [[ $ATTACH_OPTION == "ATTACH" ]] 
 then
    db2 +o "ATTACH TO ${DB2INSTANCE}"
    RETURN_CODE="$?"
    if [[ "$RETURN_CODE" -gt 0 ]]
     then
        MESSAGE "Problem attaching to instance: \"${DB2INSTANCE}\", return code: \"${RETURN_CODE}\"" PLAIN E $DEBUG
        return $RETURN_CODE
    fi
 fi

 if [[ "$OUTPUT_FILE" == "NONE" ]]
 then
    db2 -v $DB2_COMMAND
    RETURN_CODE=$?
 else
    db2 -vz $OUTPUT_FILE +o $DB2_COMMAND
    RETURN_CODE=$?
 fi

 if [[ $RETURN_CODE -gt $MAX_RETURN_CODE ]]; then
    MESSAGE "RUN_DB2CLP() Problem running command: db2 ${DB2_COMMAND}, return code: ${RETURN_CODE}" PLAIN E $DEBUG
    if [[ "$OUTPUT_FILE" == "NONE" ]]
    then
       MESSAGE "RUN_DB2CLP() View log file for further details" PLAIN E $DEBUG
    else
       MESSAGE "RUN_DB2CLP() 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  
             ;;
          *) if [[ "$OUTPUT_FILE" == "NONE" ]]
             then :
             else print "Output saved to: \"${OUTPUT_FILE}\""
             fi
            ;;
     esac
     if [[ "ATTACHED_OK" == "Y" ]]; then
       db2 +o "DETACH"
     fi
 fi
 return $RETURN_CODE
}
