/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
import com.urbancode.air.AirPluginTool

final AirPluginTool airPluginTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = airPluginTool.getStepProperties()

def message = props['message'];
def retry = props['retry'].toInteger();
def waitInSec = props['waitInSec'];
def server = props['server'];
def serverVersion = props['serverVersion']
long wait = waitInSec.toInteger() * 1000
boolean foundActive

sendMsg = { 
	if (serverVersion == '2003'){
        proc = "net send * $message".execute()    
    }
    else {
    	proc = "msg * $message".execute() 
    }
}
findUsers = { 
    foundActive = false
    proc = "query session /server:$server".execute().text
    proc.eachLine { line ->  
        //def sessionNum = line.substring(0,2).trim()
        //def sessionName = line.substring(2,20).trim()
        def username = line.substring(19,42).trim()
        //def id = line.substring(42,48).trim()
        def state = line.substring(48, 56).trim()
        if (state == 'Active') {  
            print 'State:' + state
            print ' User: ' + username
            println ''
            foundActive = true
        }
    }
    return foundActive

}

int exitCode = 1

for (i in 1..retry) {
    findUsers()
    if (foundActive) {
        println 'Retry attempt #' + i + ' of ' + retry
    	println 'Users are logged on to the server....' 
        sendMsg()
        println 'Sending message to users....'
        println ''
        sleep (wait)
    }
    else {
        exitCode = 0
        break
    }
}

if (exitCode) {
    println 'Retry limit reached'
}
else {
    println 'No Active users were found continuing the component process'
}

println 'exit code: ' + exitCode
System.exit(exitCode)
   
