/*
* 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.*
import java.text.*


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

//------------------------------------------------------------------------------
// PARSE PROPERTIES
//------------------------------------------------------------------------------

final def props = apTool.getStepProperties();
final def workDir = new File('.').canonicalFile
final def stepProps = apTool.getStepProperties();

final def hgCmd        = stepProps["source/repo/commandPath"] ?: "hg"
final def startDate    = dateParser.parseDate(stepProps['startDate'])
final def endDate      = dateParser.parseDate(stepProps['endDate'])
final def srcName      = stepProps['source'];
final def dir          = new File(workDir, stepProps['source/dirOffset'] ?: '.').canonicalFile // get checkout directory
final def remoteUrl    = stepProps['source/remoteUrl']
final def repoBaseUrl  = stepProps['source/repo/repoBaseUrl']
final def remoteUser   = stepProps['source/repo/username']
final def remotePass   = stepProps['source/repo/password'] ?: stepProps['source/repo/passScript']
final def branch       = stepProps['source/branch'] ?: 'default'
final def tag          = stepProps['source/tag']

assert startDate : 'startDate is required'
assert endDate : 'endDate is required'

// Initialize the workspace with data from remote
dir.mkdirs()

SCMQuietPeriod quietperiod = new SCMQuietPeriod();
quietperiod.hgCmd = hgCmd
quietperiod.directory = dir
quietperiod.branch = branch
quietperiod.startDate = startDate
quietperiod.endDate = endDate
quietperiod.remoteUrl = remoteUrl
quietperiod.remoteUser = remoteUser
quietperiod.remotePass = remotePass
quietperiod.repoBaseUrl = repoBaseUrl

def latestRevisionDate = quietperiod.execute()

//------------------------------------------------------------------------------
// UPLOAD LATEST CHANGE DATE
//------------------------------------------------------------------------------
if (!latestRevisionDate) {
    println "No changes detected"
}
else {
    println "Latest revision date was " + latestRevisionDate
    apTool.setOutputProperty("job/latest.change.time.${srcName}", String.valueOf(latestRevisionDate.time))
    apTool.storeOutputProperties()
}
