/*
* 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.util.Date;

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

//Input:
// repostiory url+branch+revision
// target directory
//
//

// 1) clean, if configured
// 2) clone/pull
// 3) determine revision?
// 4) update workspace to revision #3


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

final def stepProps = apTool.getStepProperties();

final def hgCmd        = stepProps['source/repo/commandPath'] ?: 'hg'
final def srcName      = stepProps['source'];
final File dir         = new File(workDir, stepProps['source/dirOffset'] ?: '.').canonicalFile // get checkout directory
final String 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 String branch    = stepProps['source/branch'] ?: 'default'

final String revision  = stepProps['revision'] ?: stepProps["buildlife/workspace.revision.$srcName"]
final Date date        = dateParser.parseDate(stepProps['date'])
final Boolean clean    = stepProps['cleanWorkspace']?.toBoolean()

//
// Perform step
//
dir.mkdirs()

SCMCheckout co = new SCMCheckout();
co.hgCmd = hgCmd
co.directory = dir
co.clean = !!clean // force nulls to be true or false
co.remoteUrl = hgHelper.calculateRepositoryUrl(repoBaseUrl, remoteUrl)
co.remoteUser = remoteUser
co.remotePass = remotePass
co.branch = branch
co.revision = revision
co.date = date
co.execute()

if (co.revision) {
    println "Updating workspace revision on buildlife to $co.revision"
    apTool.setOutputProperty("buildlife/workspace.revision.$srcName", co.revision)
    println "";
}
else if (co.date) {
    println "Updating workspace date on buildlife to $co.date"
    apTool.setOutputProperty("buildlife/workspace.date.$srcName", String.valueOf(co.date.time))
    println "";
}

apTool.storeOutputProperties()
