import com.urbancode.air.*
import com.urbancode.air.plugin.scm.*

final def apTool = new AirPluginTool(args[0], args[1])

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------

final def  workDir           = new File('.').canonicalFile
final File resourceHome      = new File(System.getenv()['PLUGIN_HOME'])
final def  props             = apTool.getStepProperties()

final def srcId              = props['source']
final def client             = props['source/client']
final boolean isLoggingIn    = Boolean.valueOf(props['source/isLoggingIn'])
final def commandPath        = props['source/repo/commandPath'] ?: 'p4'
final def port               = props['source/repo/port']
final def username           = props['source/repo/username']
final def password           = props['source/repo/password'] ?: props['source/repo/passScript']
final def charset            = props['source/repo/charset']
final def commandCharset     = props['source/repo/commandCharset']

final def dir                = new File(workDir, props['source/dirOffset']).canonicalFile
def ticketFile               = props['buildlife/ticketFile'] != null ? new File(props['buildlife/ticketFile']) : null

String depotPaths            = props['depotPaths'] ?: props["buildlife/perforce.depotPaths.${srcId}"]
boolean multiLabel           = Boolean.valueOf(props['source/isLabelingMultipleProjects'])
def labelMessage             = props['message']
def label                    = props['label']

if (label =~ /[@#*%\s]/) {
    throw new IllegalStateException('Label name can not contain @#*% or any white-space characters!')
}

if (!depotPaths) { // null or empty
    throw new IllegalStateException('No depot paths configured')
}

String[] depotPathArray = depotPaths.split(",")

dir.mkdirs()

SCMTag tag = new SCMTag()
// Command Info
tag.scmCommand = commandPath
tag.isLoggingIn = isLoggingIn
tag.client = client
tag.port = port
tag.username = username
tag.password = password
tag.charset = charset
tag.commandCharset = commandCharset

// Tag info
tag.multiLabel = multiLabel
tag.label = label
tag.labelMessage = labelMessage
tag.depotPathArray = depotPathArray

// General
if (ticketFile) {
    tag.ticketFile = ticketFile
}
tag.workDir = dir

tag.execute()