import com.urbancode.air.*

final def workDir = new File('.').canonicalFile
final def out = System.out
final def apTool = new AirPluginTool(args[0], args[1])

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

def props                       = apTool.getStepProperties()
final def dir                   = new File(workDir, props['source/dirOffset']).canonicalFile
final def scmCmd                = props['source/repo/commandPath'] ?:'tf'
final def serverUrl             = props['source/repo/serverUrl']
final def serverUserName        = props['source/repo/userName']
final def serverUserPassword    = props['source/repo/password']
final def workspaceName         = props['source/workspaceName']
final def removeAllFiles        = Boolean.valueOf(props['source/removeAllFiles'])
final def revertVersioned       = Boolean.valueOf(props['source/revertVersioned'])
final def removeUnversioned     = Boolean.valueOf(props['source/removeUnversioned'])

//------------------------------------------------------------------------------
// RUN COMMANDS
//------------------------------------------------------------------------------

CommandHelper ch = new CommandHelper(dir)

if (removeAllFiles) {
    println "Deleting directory contents for $dir"
    dir.listFiles().each { file ->
        boolean success = false;
        if (file.isFile()) {
            success = file.delete()
        } else if (file.isDirectory()) {
            success = file.deleteDir()
        }
        if (!success) {
            println("Failed to delete $file")
        }
    }
    println "Done deleting directory contents for $dir"
}
else {
    if (revertVersioned) {
        def workspaceExists = false
        try {
            def findWorkspaceCommand = [scmCmd, 'workspaces', "/server:$serverUrl", workspaceName]
            if (serverUserName && serverUserPassword) {
                findWorkspaceCommand << "/login:$serverUserName,$serverUserPassword"
            }
            ch.runCommand("Find Workspace $workspaceName", findWorkspaceCommand) { proc ->
                proc.consumeProcessErrorStream(out)
                proc.outputStream.close()
                def inWorkspaceList = false
                proc.in.eachLine { line ->
                    if (line.startsWith('-------')) {
                        inWorkspaceList = true
                    }
                    else if (inWorkspaceList && line.trim().length() > 0 && line.split(' +')[0].equalsIgnoreCase(workspaceName)) {
                        workspaceExists = true
                    }
                }
            }
        }
        catch (Exception e) {
            // we expect this if workspace does not exist
        }
        
        if (workspaceExists) {
            def undoCommand = [scmCmd, "undo", "/workspace:$workspaceName", "/server:$serverUrl",
                    '/recursive', '.', '/noprompt']
             
            if (serverUserName && serverUserPassword) {
                undoCommand << "/login:$serverUserName,$serverUserPassword"
            }                
            ch.runCommand('Run tf undo command',undoCommand)
        }
        else {
            println "Workspace '${workspaceName}' does not exist. Not able to revert versioned files."
        }
    }
    if (removeUnversioned) {
        def delimiterCount = 2
        def file
        def removeFilesCommand = [scmCmd, "folderdiff", ".", "/server:$serverUrl", "/filterLocalPathsOnly",
                "/view:targetOnly", '/recursive', '/noprompt']
                                
        if (serverUserName && serverUserPassword) {
            removeFilesCommand << "/login:$serverUserName,$serverUserPassword"
        } 
        
        ch.runCommand('Remove unversioned files', removeFilesCommand){ proc ->
            proc.consumeProcessErrorStream(out)
            proc.outputStream.close()
            proc.in.eachLine { line ->
                if (line.startsWith('===')) delimiterCount--
                else if (delimiterCount == 0 && line.trim().length() > 0) {
                    println "Deleting $line"
                    file = new File(line)
                    if (file.exists()) {
                        boolean success = false;
                        if (file.isFile()) {
                            success = file.delete()
                        }
                        else if (file.isDirectory()) {
                            success = file.deleteDir()
                        }
                        if (!success) {
                            println("Failed to delete $file")
                        }
                    }
                }
            }
        }
    }
}
