/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
import java.text.SimpleDateFormat
import com.urbancode.air.*
import com.urbancode.air.plugin.scm.*;

final def workDir = new File('.').canonicalFile
final def CommandHelper ch = new CommandHelper(workDir)
final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def dateParser = new DateParser()

//------------------------------------------------------------------------------
// PARSE PROPERTIES
//------------------------------------------------------------------------------
def props = apTool.getStepProperties()

final def srcName       = props['source']
final def svnExe        = props['source/repo/commandPath'] ?: "svn"
def svnRoot             = props['source/repo/repositoryBaseUrl'] // not final so we can prepend http:// if no protocol is specified
final def username      = props['source/repo/username']
final def password      = props['source/repo/password'] ?: props['source/repo/passScript']
final boolean isSvnRepo   = Boolean.valueOf(props['source/repo/isSvnRepo'])
final def svnTrunk      = props['source/projectTrunkPath']

final File dir          = new File(workDir, props['source/dirOffset']).canonicalFile

final def startRevision = props['startRevision']
final def endRevision   = props['endRevision']
final def startDate     = dateParser.parseDate(props['startDate'])
final def endDate       = dateParser.parseDate(props['endDate'])

def userExcludes          = props['source/excludeUsers'] ?: ""
def fileFilters           = props['source/fileFilters'] ?: ""

//
// Run Step
//
dir.mkdirs()

SCMQuietPeriod quietPeriod = new SCMQuietPeriod();
quietPeriod.scmCommand = svnExe;
quietPeriod.username = username;
quietPeriod.password = password;
quietPeriod.directory = dir;
quietPeriod.isSvnRepo = isSvnRepo;

quietPeriod.startRevision = startRevision
quietPeriod.endRevision = endRevision
quietPeriod.startDate = startDate
quietPeriod.endDate = endDate
quietPeriod.svnTrunk = svnTrunk
quietPeriod.svnRoot = svnRoot

quietPeriod.changeSetFilter.setUserExcludes(userExcludes);
quietPeriod.changeSetFilter.setFileFilters(fileFilters);

Date latestRevisionDate = quietPeriod.execute()

//------------------------------------------------------------------------------
// UPLOAD LATEST CHANGE DATE
//------------------------------------------------------------------------------
if (latestRevisionDate == null) {
    println('No changes detected')
}
else {
    apTool.setOutputProperty("job/latest.change.time.${srcName}", String.valueOf(latestRevisionDate.time))
    apTool.storeOutputProperties()
    println "Latest Revision Date: " + latestRevisionDate
    println "";
}