/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
import com.urbancode.air.AirPluginTool

final def workDir = new File('.').canonicalFile
final def pluginTool = new AirPluginTool(args[0], args[1])
final def props = pluginTool.stepProperties

final def dirOffset = props['dirOffset']
final def fileName = props['file']
final def regex = props['regex']
final def timeout = props['timeout'].toInteger()
final def failIfFound = props['failIfFound'].toBoolean()

if (dirOffset) {
    workDir = new File(workDir, dirOffset)
}

def endTime = System.currentTimeMillis() + (timeout * 1000)
def done = false
def file = new File(workDir, fileName)
def startOffset = file.exists() ? file.size() : 0
def reader
def line

println "Monitoring file: ${file.canonicalPath}"
println "Regular Expression: $regex"
println "Timeout: $timeout (s)"
println "Fail if found: $failIfFound"

while (!done && endTime > System.currentTimeMillis()) {
    if (file.exists()) {
        reader = file.newReader()
        reader.skip(startOffset)
    }

    if (reader) {
        line = reader.readLine()
        while (line != null) {
            if (line =~ regex) {
                done = true
                println "Found a matching line:"
                println line
                break
            }
            else {
                line = reader.readLine()
            }
        }

        if (!done) {
            sleep 500
        }
    }
    else {
        sleep 500
    }
}

if (done) {
    if (failIfFound) {
        System.exit 1
    }
    else {
        System.exit 0
    }
}
else {
    println "Did not find a match! Timing out..."
    if (failIfFound) {
        System.exit 0
    }
    else {
        System.exit 1
    }
}
