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

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 dirOffset             = props['source/dirOffset'] ?: '.'
final def dir                   = new File(workDir, 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)

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().startsWith(workspaceName + ' ')) {
                workspaceExists = true
            }
        }
    }
}
catch (Exception e) {
    // we expect this if workspace does not exist
}

if (removeAllFiles) {
    if (workspaceExists) {
        def deleteCommand = [scmCmd, 'workspace', '/delete', workspaceName, "/server:$serverUrl", '/noprompt']
        if (serverUserName && serverUserPassword) {
            deleteCommand << "/login:$serverUserName,$serverUserPassword"
        }
        ch.runCommand('Delete workspace', deleteCommand)
    }
    
    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) {
        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")
                        }
                    }
                }
            }
        }
    }
}
