import com.urbancode.air.*;
import com.urbancode.air.plugin.automation.*;
import java.lang.reflect.Array;

XTrustProvider.install();

final File resourceHome = new File(System.getenv()['PLUGIN_HOME'])
final def buildLifeId = System.getenv()['BUILD_LIFE_ID']

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

final def serverUrl       = props['automation/serverUrl']
final def serverVersion   = props['automation/serverVersion']
final def username        = props['automation/username']
final def password        = props['automation/passwordScript'] ?: props['automation/password']

final def actionName = props['actionName']
final def additionalComment = props['additionalComment']
final def issueIdPattern  = props['issueIdPattern']

//------------------------------------------------------------------------------
// Script content
//------------------------------------------------------------------------------

println "Server:\t$serverUrl";
println "Action:\t$actionName";
println "Issue Keys:\t$issueIdPattern";
println "Additional Comment:\t$additionalComment";

// Load the appropriate Jira Soap Classes into classloader
final def jiraSoapJar = new File(resourceHome, "jira-${serverVersion}.wsdl.jar")
assert jiraSoapJar.isFile();
this.class.classLoader.rootLoader.addURL(jiraSoapJar.toURL())
def JiraSoapServiceServiceLocator = Class.forName('com.atlassian.jira.rpc.soap.jirasoapservice_v2.JiraSoapServiceServiceLocator');
def RemoteIssue = Class.forName('com.atlassian.jira.rpc.soap.beans.RemoteIssue')
def RemoteComment = Class.forName('com.atlassian.jira.rpc.soap.beans.RemoteComment')
def RemoteFieldValue = Class.forName('com.atlassian.jira.rpc.soap.beans.RemoteFieldValue')
def RemotePermissionException = Class.forName('com.atlassian.jira.rpc.exception.RemotePermissionException')

// connect to Jira
String fullAddress = serverUrl + "/rpc/soap/jirasoapservice-v2";
if (!fullAddress.startsWith("http")) {
    fullAddress = "http://" + fullAddress;
}
def locator = JiraSoapServiceServiceLocator.newInstance();
locator.jirasoapserviceV2EndpointAddress = fullAddress;
def jiraSoapService = locator.getJirasoapserviceV2();
def sessionToken = jiraSoapService.login(username, password);
try {
    XMLHelper helper = new XMLHelper(issueIdPattern)
    helper.getChangesets()
    def issueIdSet = helper.getIssueIdSet()

    issueIdSet.each { issueKey ->
        try {
            def returnedIssue = jiraSoapService.getIssue(sessionToken, issueKey)
            if (!returnedIssue) {
                println("\tSkipping Issue "+issueKey+": Specified Issue not found.");
            }
            else {
                def action = jiraSoapService.getAvailableActions(sessionToken, issueKey).find{actionName == it.name}
                if (action == null) {
                    println("\tSkipping Issue $issueKey: Specified Action $actionName was not available.");
                }
                else {
                    def fields = jiraSoapService.getFieldsForAction(sessionToken, issueKey, action.id)

                    def fieldValues = []
                    for (def field : fields) {
                        if (field.name == 'assignee') {
                            fieldValues << RemoteFieldValue.newInstance('assignee', [issue.assignee] as String[])
                        }
                    }
                    def remoteFieldValueArray = Array.newInstance(RemoteFieldValue, 0)
                    jiraSoapService.progressWorkflowAction(sessionToken, issueKey, action.id, fieldValues.toArray(remoteFieldValueArray))
                    println("Successfully performed $action.name on issue $issueKey");
                    if (additionalComment) {
                        def comment = RemoteComment.newInstance()
                        comment.setBody(additionalComment);
                        jiraSoapService.addComment(sessionToken, issueKey, comment)
                        println("Successfully added new comment to issue $issueKey");
                    }
                }
            }
        }
        catch (Exception e) {
            if (!RemotePermissionException.isInstance(e)) {
                throw e;
            }
            else {
                e.printStackTrace();
            }
        }
    }
}
finally {
    jiraSoapService.logout(sessionToken)
}
