/*
* 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();
def apTool = new AirPluginTool(this.args[0], this.args[1])

//------------------------------------------------------------------------------
// PARSE PROPERTIES
//------------------------------------------------------------------------------
final def stepProps = apTool.getStepProperties();

final File workDir = new File('.').canonicalFile

// Repo
final String scmCmd     = stepProps['source/repo/commandPath']
final String baseUrl    = stepProps['source/repo/repoBaseUrl']
final String username   = stepProps['source/repo/username']
final String password   = stepProps['source/repo/password'] ?: stepProps['source/repo/passScript']

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

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

// Execute
dir.mkdirs()

SCMQuietPeriod quietPeriod = new SCMQuietPeriod();
quietPeriod.directory  = dir;
quietPeriod.scmCommand = scmCmd;
quietPeriod.remoteBaseUrl  = baseUrl;
quietPeriod.remoteUser = username;
quietPeriod.remotePass = password;
quietPeriod.remoteUrl  = remoteUrl;
quietPeriod.remoteName = remoteName;
quietPeriod.branch     = branch;

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
}
