#!/usr/bin/env groovy
/*
* 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 workDir = new File('.').canonicalFile

final def directoryOffset = props['directoryOffset']
final def fileName = props['fileName']
final def regex = props['regex']
final def failOnFound = Boolean.valueOf(props['failOnFound'])

//
// Validation
//

if (directoryOffset) {
    workDir = new File(workDir, directoryOffset).canonicalFile
}

if (workDir.isFile()) {
    throw new IllegalArgumentException("Working directory ${workDir} is a file!")
}



//
// Create workDir and scriptFile
//

// ensure work-dir exists
workDir.mkdirs()

def file = new File(workDir, fileName)

if (!file.exists()) {
    println "File $fileName does not exist in ${workDir.canonicalPath}"
    System.exit 1
}

println "File: $fileName"
println "Regular Expression: $regex"
println "Fail On Match: $failOnFound"

def antBuilder = new AntBuilder()

antBuilder.loadfile(property:"found", srcfile:"${file.canonicalPath}") {
    filterchain() {
        linecontainsregexp() {
            regexp(pattern:"$regex")
        }
    }
}

def result = antBuilder.project.properties['found']

if (result) println "Match found!"
println "Match: $result"

if ((result && failOnFound) || (!result && !failOnFound)) {
    System.exit 1
}
else {
    System.exit 0
}
