/*
* 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(this.args[0], this.args[1]);
final SCMHelper scmHelper = new SCMHelper();

//------------------------------------------------------------------------------
// PARSE PROPERTIES
//------------------------------------------------------------------------------
final File workDir = new File('.').canonicalFile

final def stepProps = apTool.getStepProperties();

final def accurevCmd            = stepProps['source/repo/commandPath'] ?: 'accurev'
final String host               = stepProps['source/repo/repoHost']
final String username           = stepProps['source/repo/username']
final String password           = stepProps['source/repo/password'] ?: stepProps['source/repo/passScript']

final def srcName               = stepProps['source'];
final File dir                  = new File(workDir, stepProps['source/dirOffset'] ?: '.').canonicalFile // get checkout directory
final String streamName         = stepProps['source/stream']
final String userExcludesString = stepProps['source/excludeUsers'] ?: ''
final String  fileFiltersString = stepProps['source/fileFilters'] ?: '';

final def startRevision         = stepProps['startRevision'] ?: ''
final def endRevision           = stepProps['endRevision'] ?: ''
final def startDate             = dateParser.parseDate(stepProps['startDate'])
final def endDate               = dateParser.parseDate(stepProps['endDate'])

// create the directory ahead of time
dir.mkdirs()

// Execute
SCMQuietPeriod quietPeriod = new SCMQuietPeriod();
quietPeriod.scmCommand = accurevCmd;
quietPeriod.host = host;
quietPeriod.username = username;
quietPeriod.password = password;
quietPeriod.directory = dir;
quietPeriod.streamName = streamName;

quietPeriod.startRevision = startRevision
quietPeriod.endRevision = endRevision
quietPeriod.startDate = startDate
quietPeriod.endDate = endDate

quietPeriod.changeSetFilter.setUserExcludes(userExcludesString);
quietPeriod.changeSetFilter.setFileFilters(fileFiltersString);

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
}
