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

//------------------------------------------------------------------------------
// 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();

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 def srcName           = stepProps['source'];
final File dir              = new File(workDir, stepProps['source/dirOffset'] ?: '.').canonicalFile // get checkout directory
final String streamName     = stepProps['source/stream']
final def popLocations      = stepProps['source/popLocations']?.readLines().findAll { it }

// look for date based checkout (buildlife, then actual workspace date)
final Date date             = dateParser.parseDate(stepProps['date']) // this is from actualWorkspaceDate
final Date blDate           = dateParser.parseDate(stepProps["buildlife/workspace.date.$srcName"]); // from checkout step

// look for revision from step (regular workspace date), then buildlife, then source config
final String revision       = stepProps['revision'];
final String blRevision     = stepProps["buildlife/workspace.revision.$srcName"];
final String sourceRevision = stepProps['source/revision'];

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

//
// Perform step
//
SCMCheckout co = new SCMCheckout();
co.scmCommand = accurevCmd;
co.host = host;
co.username = username;
co.password = password;
co.directory = dir
co.streamName = streamName
co.popLocations = popLocations
co.revision = revision ?: blRevision ?: sourceRevision;
co.date = date ?: blDate
co.execute()

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

apTool.setOutputProperty("buildlife/accurev.stream.$srcName", streamName)

apTool.storeOutputProperties()
