/*
* 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
import com.urbancode.air.CommandHelper

final def tool = new AirPluginTool(args[0], args[1])
final def cmdHelper = new CommandHelper(new File('.').canonicalFile)
final def props = tool.getStepProperties()

def retry = props['retry'].toInteger()
def waitInSec = props['waitInSec']
def server = props['server']?.trim()
def sessionFilter = props['sessionFilter']?.trim()
def sessionStateFilter = props['sessionStateFilter']?.trim()
long wait = waitInSec.toInteger() * 1000

def findSessions = {
    def sessionSet = [] as Set
    def cmdArgs = ['qwinsta']
    if (server && server.length() > 0) {
        cmdArgs << "/server:$server"
    }

    cmdHelper.runCommand("Query sessions", cmdArgs) { proc->
        proc.out.close()
        proc.consumeProcessErrorStream(System.err)
        proc.in.eachLine { line, index ->
            println "\t$line"
            if(line && line.trim().length() > 0 && index > 1) {
                def sessionName = line.substring(1,19).trim()
                def state = line.substring(48, 56).trim()
                def acceptable = true
                if (sessionFilter && sessionFilter.length() > 0) {
                    def matcher = sessionName =~ sessionFilter
                    if (!matcher.matches()) {
                        acceptable = false
                    }

                }
                if (sessionStateFilter && sessionStateFilter.length() > 0) {
                    def stateMatcher = state =~ sessionStateFilter
                    if (!stateMatcher.matches()) {
                        acceptable = false
                    }
                }
                if (acceptable) {
                    if (sessionName.length() > 0) {
                        sessionSet << sessionName
                    }
                    else {
                        def sessionId = line.substring(41, 47).trim()
                        sessionSet << sessionId
                    }
                }
            }
        }
    }

    return sessionSet
}

def logOffSessions = { sessionSet ->
    def result = true
    if (sessionSet) {
        println "Logging sessions off: "
        sessionSet.each { session ->
            println '--------------------------------------------------'
            println "\t$session"
            try {
                def cmdArgs = ['logoff', session]
                if (server && server.length() > 0) {
                    cmdArgs << "/server:$server"
                }
                cmdArgs << '/V'

                cmdHelper.runCommand("", cmdArgs)
            }
            catch (Exception e) {
                println "\tFailed to perform logoff: ${e.message}"
                result = false
            }
        }
    }
    return result
}

try {
    def sessionSet = findSessions()

    if (retry > 0) {
        for (i in 1..retry) {
            if (sessionSet.size() > 0) {
                println 'Retry attempt #' + i + ' of ' + retry
                println 'Found matching sessions....'
                sessionSet.each { session->
                    println "\t$session"
                }
                println '-----------------------------------------------'
                sleep (wait)
                sessionSet.clear()
                sessionSet = findSessions()
            }
            else {
                println "Did not find any sessions matching the criteria."
                break
            }
        }
    }
    else {
        println 'No wait requested.'
    }

    if (sessionSet.size() > 0) {
        println 'Done waiting, logging sessions off.'
        if (!logOffSessions(sessionSet)) {
            System.exit 1
        }
    }
    else {
        println 'No sessions matching criteria found, nothing to do!'
    }
}
catch (Exception e) {
    e.printStackTrace()
    System.exit 1
}
System.exit 0
