/*
* 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.*

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

final def apTool = new AirPluginTool(this.args[0], this.args[1]);
final def dateParser = new DateParser();

final SCMHelper scmHelper = new SCMHelper();
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 File dir            = new File(workDir, stepProps['source/dirOffset'] ?: '.').canonicalFile // get checkout directory
final String srcName      = stepProps['source'];
final String streamName   = stepProps['source/stream']
final String newLabelName = stepProps['label']

// use buildlife revision (from checkout), then buildlife revision
final String blRevision   = stepProps["buildlife/workspace.revision.$srcName"]
final String srcRevision  = stepProps['source/revision']

// use step-date, buildlife date (from checkout), then global workspace date
final Date date           = dateParser.parseDate(stepProps['date'])
final Date blDate         = dateParser.parseDate(stepProps["buildlife/workspace.date.$srcName"])
final Date wsDate         = dateParser.parseDate(stepProps['buildlife/workspace.date']);

//------------------------------------------------------------------------------
// PREPARE COMMAND LINE
//------------------------------------------------------------------------------

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

SCMTag tag = new SCMTag();
tag.scmCommand = accurevCmd;
tag.host = host;
tag.username = username;
tag.password = password;
tag.directory = dir
tag.streamName = streamName
tag.revision = blRevision ?: srcRevision
tag.date = date ?: blDate ?: wsDate;
tag.tagName = newLabelName
tag.execute()