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

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

final def props             = apTool.getStepProperties();
final File dir              = new File(workDir, props['source/dirOffset'] ?: '.').canonicalFile

final def commandPath               = props['source/repo/commandPath'] ?: "scm"
final def serverUrl                 = props['source/repo/serverUrl']
final def username                  = props['source/repo/username']
final def password                  = props['source/repo/password']

final def workspace                 = props['source/workspace']
final def stream                    = props['source/stream']
final def baseline                  = props['source/baseline']
final def snapshot                  = props['source/snapshot']
final def components                = props['source/components']
final def buildSnapshot             = props['source/buildSnapshot']
final def buildSnapshotDescription  = props['source/buildSnapshotDescription']?:' '
final def listSnapshotDateFormat    = props['source/repo/listSnapshotDateFormat']
final def userExcludes              = props['source/excludeUsers'] ?: ''
final def fileFilters               = props['source/fileFilters'] ?: ''
final def isIncludeRoot             = Boolean.valueOf(props['source/isIncludeRoot'])
final def isForce                   = Boolean.valueOf(props['source/isForce'])

dir.mkdirs()

SCMStep rtcHelper = new SCMStep()
rtcHelper.command = commandPath
rtcHelper.serverUrl = serverUrl
rtcHelper.username = username
rtcHelper.password = password
rtcHelper.directory = dir

rtcHelper.workspace = workspace
rtcHelper.stream = stream
rtcHelper.baseline = baseline
rtcHelper.snapshot = snapshot
rtcHelper.components = components
rtcHelper.buildSnapshot = buildSnapshot
rtcHelper.buildSnapshotDescription = buildSnapshotDescription
rtcHelper.listSnapshotDateFormat = listSnapshotDateFormat
rtcHelper.isIncludeRoot = isIncludeRoot
rtcHelper.isForce = isForce

if (!dir.exists()) {
    println("Directory ${dir} does not exist so nothing to cleanup!")
}
else if (dir.isFile()) {
    throw new Exception("Specified working directory ${dir} is a file!")
}
else {
    // try to get the status of the local workspace, if there is none we just need to remove everything
    try {
        rtcHelper.undo(dir)
    }
    catch (Exception e) {
        e.printStackTrace()
        println "No local workspace detected in ${dir}!"
        rtcHelper.cleanup(dir)
    }
}

