#-------------------------------------------------------------------------------
# Function to list applications and wait until they're all disconnected.
# The output file is deliberately overwriteable by members of the SYSADM_GROUP.
# Arguments: $1instance name  
#            $2 Partition count for this instance.    
#            $3 Korn Shell debug mode (+x=off, -x=on).
#-------------------------------------------------------------------------------
 
LIST_APPLICATIONS()
{
 INSTNAME="$1"
 NO_OF_PARTITIONS="$2" 
 set "$3"
 print "\n________________________________________"
 print "Checking for connections to the database"
 typeset -i COUNT=0
 typeset -i ITERATIONS=0
 typeset -i MAX_ITERATIONS=120  # Wait for 2 hours (120 x 60 seconds)
 CHECK_START_TIME=`date "+%d/%m/%Y %T"`
 LISTAPPS_FILE="/tmp/listapps_${INSTNAME}"
 DELETE_FILE "$LISTAPPS_FILE" "SILENT" "$3"
 
 while [[ "$COUNT" -lt "$NO_OF_PARTITIONS" ]]
 do
    # Command returns the following if no applications are connected:
    #   SQL1611W  No data was returned by Database System Monitor.  SQLSTATE=00000
    #
    if [[ "$NO_OF_PARTITIONS" -gt 1 ]]; then
       db2_all '||
                print "partition: "$DB2NODE
                db2 -v LIST APPLICATIONS; ' > "$LISTAPPS_FILE"
    else
       db2 "LIST APPLICATIONS SHOW DETAIL"  > "$LISTAPPS_FILE"
    fi
    COUNT=`grep -c SQL1611W "$LISTAPPS_FILE"`
    let ITERATIONS=ITERATIONS+1
    if [[ "$ITERATIONS" -ge "$MAX_ITERATIONS" ]]; then
       CHECK_STOP_TIME=`date "+%d/%m/%Y %T"`
       print "\n***"
       print "***  I'm sick of waiting for applications to disconnect so I'm giving up!"
       print "***"
       print "***  Started checking connections at: ${CHECK_START_TIME}"
       print "***  Stopped checking connections at: ${CHECK_STOP_TIME}"
       print "***"
       print "***  Applications list:"
       print "***\n"
       chmod 664 "$LISTAPPS_FILE"
       cat "$LISTAPPS_FILE"
       print "________________________________________\n"
       return 1    # signal caller that there are still connections
    fi
    sleep 60
 done

 chmod u=rw,g=rw,o=r "$LISTAPPS_FILE"
 print "No applications connected to database, continuing..."
 print "________________________________________\n"
}
