/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Build
 * (c) Copyright IBM Corporation 2015. 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.AirPluginTool
import com.urbancode.air.plugin.scm.*
import com.urbancode.air.DateParser

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

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------
final def dateParser = new DateParser()
final def apTool = new AirPluginTool(this.args[0], this.args[1])

final def stepProps = apTool.getStepProperties()

// Repo
final def commandPath = stepProps['source/repo/commandPath']
final def broker = stepProps['source/repo/broker']
final def username = stepProps['source/repo/username']
final def password = stepProps['source/repo/password'] ?: stepProps['source/repo/passScript']

// Source
final def srcName = stepProps['source'];
final def dir = new File(workDir, stepProps['source/dirOffset'] ?: '.').canonicalFile //log file directory
final def pkg = stepProps['source/package']
final def project = stepProps['source/project']
final def viewPath = stepProps['source/viewPath']
final def state = stepProps['source/state']
final String userExcludesString = stepProps['source/excludeUsers'] ?: ''
final String fileFiltersString  = stepProps['source/fileFilters'] ?: '';


// quietPeriod
final def startDate = dateParser.parseDate(stepProps['startDate'])
final def endDate = dateParser.parseDate(stepProps['endDate'])

//
// Perform quietPeriod
//
dir.mkdirs()

SCMQuietPeriod quietPeriod = new SCMQuietPeriod()
quietPeriod.directory = dir
quietPeriod.commandPath = commandPath
quietPeriod.scmCmd = 'hsv'
quietPeriod.broker = broker
quietPeriod.username = username
quietPeriod.password = password
quietPeriod.project = project
quietPeriod.viewPath = viewPath
quietPeriod.state = state
quietPeriod.pkg = pkg
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
}