#!/usr/bin/env groovy
/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. 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.AirPluginTool
import com.urbancode.air.CommandHelper

final AirPluginTool airPluginTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = airPluginTool.getStepProperties()

final File PLUGIN_HOME = new File(System.getenv().get("PLUGIN_HOME"))

def workDir = new File('.').canonicalFile

final def directoryOffset = props['directoryOffset']
final def caclsPath = props['caclsPath']
final def caclsType = props['caclsType']
final def useXcacls = (caclsType.toLowerCase().equals("xcacls"))
final def useIcacls = (caclsType.toLowerCase().equals("icacls"))
final def includeSubfolders = Boolean.valueOf(props['includeSubfolders'])
final def editInstead = Boolean.valueOf(props['editInstead'])
final def ignoreAccessDenied = Boolean.valueOf(props['ignoreAccessDenied'])
final def grantRights = props['grantRights']
final def revokeUser = props['revokeUser']
final def replaceUserRights = props['replaceUserRights']
final def denyUser = props['denyUser']
final def noVerify = Boolean.valueOf(props['noVerify'])
final def files = props['files']

//
// Validation
//

if (directoryOffset) {
    workDir = new File(workDir, directoryOffset).canonicalFile
}

if (workDir.isFile()) {
    throw new IllegalArgumentException("Working directory ${workDir} is a file!")
}

if (revokeUser && !editInstead && !useIcacls) {
    throw new IllegalArgumentException('Cannot use \'Revoke user\'s rights\' without ' +
                '\'Edit ACLs instead of replacing\' option checked!')
}

if (editInstead && useIcacls) {
    throw new IllegalArgumentException('Cannot use \'Edit Instead\' with \'ICACLS\' option selected!')
}

if (noVerify && !useXcacls) {
    throw new IllegalArgumentException('Cannot use \'Replace without verify\' without \'Use XCACLS\' option selected!')
}

//
// Create workDir and scriptFile
//

// ensure work-dir exists
workDir.mkdirs()

def caclsExe = ''
if (caclsPath) {
    caclsExe += caclsPath + (caclsPath.endsWith('\\')?'':'\\')
}

caclsExe += (caclsType)

//
// Build Command Line
//
def cmdHelper = new CommandHelper(workDir)
def commandLine = [caclsExe]
def icaclsFlags = []

files.trim().split('\n').each { file ->
    if (file && file.trim().length() > 0) {
            commandLine << file.trim()
    }
}

if (includeSubfolders) {
    if (useIcacls) {
        icaclsFlags << '/T'
    } else {
        commandLine << '/T'
    }
}

if (editInstead) {
    commandLine << '/E'
}

if (ignoreAccessDenied) {
    if (useIcacls) {
        icaclsFlags << '/C'
    } else {
        commandLine << '/C'
    }
}


if (grantRights && grantRights.trim().length() > 0) {
    commandLine << (!useIcacls ? '/G' : '/grant:r')
    grantRights.trim().split('\n').each { right ->
        if (right && right.trim().length() > 0) {
            commandLine << right.trim()
        }
    }
}

if (revokeUser && revokeUser.trim().length() > 0) {
    commandLine << (!useIcacls ? '/R' : '/remove:g')
    revokeUser.trim().split('\n').each { user ->
        if (user && user.trim().length() > 0) {
            commandLine << user.trim()
        }
    }
}

if (replaceUserRights && replaceUserRights.trim().length() > 0) {
    //replace is not an explicit flag in icacls [/grant] without [:r] replaces
    commandLine << (!useIcacls ? '/P' : '/grant')
    replaceUserRights.trim().split('\n').each { right ->
        if (right && right.trim().length() > 0) {
            commandLine << right.trim()
        }
    }
}

if (denyUser && denyUser.trim().length() > 0) {
    commandLine << (!useIcacls ? '/D' : '/deny')
    denyUser.trim().split('\n').each { user ->
        if (user && user.trim().length() > 0) {
            commandLine << user.trim()
        }
    }
}

icaclsFlags.each { flag ->
    commandLine << flag
}

if (noVerify) {
    commandLine << '/Y'
}


// print out command info
println("")
println("working directory: ${workDir.path}")


//def proc = cmdHelper.execute(null, workDir)
try {
    cmdHelper.runCommand("Running ${caclsType}:", commandLine)
} catch (Exception e) {
    println "Error running command: ${e.message}"
    System.exit 1
}
System.exit(0)
