/*
* 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])


//------------------------------------------------------------------------------
// PARSE PROPERTIES
//------------------------------------------------------------------------------
final def stepProps = apTool.getStepProperties()
final def workDir = new File('.').canonicalFile

// Repo
final String scmCmd     = stepProps['source/repo/commandPath'] ?: "git"
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 remoteUrl     = stepProps['source/remoteUrl']
final String remoteName    = stepProps['source/remoteName']
final String branch        = stepProps['source/branch']
//final String sourceRevision = stepProps['source/revision']; should use revision from checkout step
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']) // explicit start date ?: startBuildLife.actualWorkspaceDate
final def endDate       = dateParser.parseDate(stepProps['endDate'])   // explicit end date ?: buildLife.actualWorkspaceDate
final String changesUrl = stepProps['changesUrl']

if (!endRevision) {
    // We need to use HEAD because changelog --until=${revision} is exclusive and therefore we would not
    // get the most recent change
    endRevision = "HEAD"//ahpTool.getBuildLifeProperties()["workspace.revision.$srcName"]
}

dir.mkdirs()
//
// Execute
//
SCMChangelog step = new SCMChangelog();
step.directory  = dir;
step.scmCommand = scmCmd;
step.remoteBaseUrl  = baseUrl;
step.remoteUser = username;
step.remotePass = password;
step.remoteUrl  = remoteUrl;
step.remoteName = remoteName;
step.branch     = branch;

step.startRevision = startRevision
step.endRevision = endRevision // Use workspace revision as end point
step.startDate = startDate
step.endDate = endDate // Use workspace revision as end point
step.changesUrl = changesUrl

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

step.execute()