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

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------
final def workDir = new File('.').canonicalFile

final def TFS_DATE_FORMAT = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'Z'")
TFS_DATE_FORMAT.timeZone = TimeZone.getTimeZone("UTC")

final def dateParser = new DateParser();
final def apTool = new AirPluginTool(args[0], args[1]);

final def props             = apTool.getStepProperties();

final def srcName           = props['source']
final String scmCmd         = props['source/repo/commandPath'] ?: "tf"
final def dirOffset         = props['source/dirOffset'] ?: '.'
final def dir               = new File(workDir, dirOffset).canonicalFile // get checkout directory
final def serverUrl         = props['source/repo/serverUrl']
final def serverUserName    = props['source/repo/userName']
final def serverPassword    = props['source/repo/password'] ?: props['source/repo/passScript']
final def tfsVersion        = props['source/repo/serverVersion']
final def sourceLocation    = props['source/sourceLocation']
final def label             = props['source/label']
final def changeset         = props['source/changeset']
final def startDate         = dateParser.parseDate(props['startDate'])
final def endDate           = dateParser.parseDate(props['endDate'])
final def userExcludes      = props['source/userExcludes']
final def fileFilters       = props['source/fileFilters']
final def tfToolPath        = props['tfToolPath']

//------------------------------------------------------------------------------
// RUN QUIET PERIOD
//------------------------------------------------------------------------------
dir.mkdirs()

Date latestChangeDate = new Date(1)

SCMQuietPeriod qp = new SCMQuietPeriod()
qp.scmCommand = scmCmd
qp.workDir = dir
qp.serverUrl = serverUrl
qp.serverUserName = serverUserName
qp.serverPassword = serverPassword
qp.tfsVersion = tfsVersion
qp.sourceLocation = sourceLocation

qp.label = label
qp.changeset = changeset
qp.startDate = startDate
qp.endDate = endDate

qp.changeSetFilter.setUserExcludes(userExcludes);
qp.changeSetFilter.setFileFilters(fileFilters);
qp.tfToolPath = tfToolPath

latestChangeDate = qp.execute()

if (latestChangeDate == new Date(1)) {
    println('No changes detected')
}
else {
    apTool.setOutputProperty("job/latest.change.time.${srcName}", String.valueOf(latestChangeDate.time))
    apTool.storeOutputProperties()
    println "Latest Revision Date: " + latestChangeDate
}
