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 (!reader && file.exists()) {
        reader = file.newReader()
        reader.skip(startOffset)
    }

    if (reader) {
        line = reader.readLine()
        while (line) {
            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
    }
}
