/*
* 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.DateParser
import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.scm.*

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 //checkout directory
final def snapshot = stepProps['source/snapshot']
final def version = stepProps['source/version']
final def checkoutMethod = stepProps['source/checkoutMethod']
final def pkg = stepProps['source/package']
final def project = stepProps['source/project']
final def state = stepProps['source/state']
final def viewPath = stepProps['source/viewPath']
final def includeFiles = stepProps['source/includeFiles']

// Step

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

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

SCMCheckout step = new SCMCheckout()
step.directory = dir
step.commandPath = commandPath
step.scmCmd = 'hco'
step.broker = broker
step.username = username
step.password = password
step.project = project
step.viewPath = viewPath
step.state = state
step.snapshot = snapshot
step.version = version
step.pkg = pkg
step.checkoutMethod = checkoutMethod
step.includeFiles = includeFiles?.tokenize("\n") as String[]
step.date = blDate ?: date
step.execute()

if (step.date) {
    if (blDate != step.date) {
        println "Updating workspace date on buildlife to $step.date"
        apTool.setOutputProperty("buildlife/workspace.date.$srcName", "${step.date}")
        println ""
    }
}

apTool.storeOutputProperties()
