Add ability to reconfigure gerrit trigger

 Add ability manage build of patches

https://mirantis.jira.com/browse/PROD-20769

Change-Id: I886eff6e5ad82e582c44bd13e362e73b985a100f
diff --git a/README.rst b/README.rst
index c5df377..69a295d 100644
--- a/README.rst
+++ b/README.rst
@@ -815,6 +815,10 @@
             email: "jenkins@domain.local"
             auth_key_file: "/var/jenkins_home/.ssh/id_rsa"
             frontendURL: "https://gerrit.domain.local"
+            build_current_patches_only: true
+            abort_new_patchsets: false
+            abort_manual_patchsets: false
+            abort_same_topic: false
             authkey: |
               SOMESSHKEY
           server2:
@@ -824,6 +828,10 @@
             email: "jenkins@domain.local"
             auth_key_file: "/var/jenkins_home/.ssh/id_rsa"
             frontendURL: "https://gerrit2.domain.local"
+            build_current_patches_only: true
+            abort_new_patchsets: false
+            abort_manual_patchsets: false
+            abort_same_topic: false
             authkey: |
               SOMESSHKEY
 
diff --git a/_states/jenkins_gerrit.py b/_states/jenkins_gerrit.py
index 26b1259..a2b0e95 100644
--- a/_states/jenkins_gerrit.py
+++ b/_states/jenkins_gerrit.py
@@ -15,7 +15,10 @@
 
 
 def present(name, hostname, username, frontendurl, auth_key_file, authkey,
-            port="29418", auth_key_file_password=None, email="", proxy=""):
+            port="29418", build_current_patches_only="false",
+            abort_new_patchsets="false", abort_manual_patchsets="false",
+            abort_same_topic="false", auth_key_file_password=None, email="",
+            proxy=""):
     """
     Jenkins gerrit-trigger state method
 
@@ -26,6 +29,10 @@
     :param port: server ssh port
     :param proxy: proxy url (optional)
     :param frontendurl: server frontend URL
+    :param build_current_patches_only: build current patches only (optional)
+    :abort_new_patchsets: abort new patchsets (optional)
+    :abort_manual_patchsets: abort manual patchsets (optional)
+    :abort_same_topic: abort same topic (optional)
     :param auth_key_file: path to key file
     :param authkey: ssh key
     :param auth_key_file_password: password for keyfile (optional)
@@ -35,7 +42,7 @@
         'salt://jenkins/files/groovy/gerrit.template',
         __env__)
     return __salt__['jenkins_common.api_call'](name, template,
-                        ["CREATED", "EXISTS"],
+                        ["CREATED", "CHANGED", "SKIPPED"],
                         {
                             "name": name,
                             "hostname": hostname,
@@ -44,8 +51,12 @@
                             "username": username,
                             "email": email if email else "",
                             "frontendurl": frontendurl,
+                            "build_current_patches_only": build_current_patches_only if build_current_patches_only else "false",
+                            "abort_new_patchsets": abort_new_patchsets if abort_new_patchsets else "false",
+                            "abort_manual_patchsets": abort_manual_patchsets if abort_manual_patchsets else "false",
+                            "abort_same_topic": abort_same_topic if abort_same_topic else "false",
                             "auth_key_file": auth_key_file,
                             "authkey": authkey,
-                            "auth_key_file_password": auth_key_file_password if auth_key_file_password else None
+                            "auth_key_file_password": auth_key_file_password if auth_key_file_password else ""
                         },
                         "Gerrit server")
diff --git a/jenkins/client/gerrit.sls b/jenkins/client/gerrit.sls
index c540b20..24c4abf 100644
--- a/jenkins/client/gerrit.sls
+++ b/jenkins/client/gerrit.sls
@@ -11,6 +11,10 @@
   - email: {{ gerrit.get('email', '') }}
   - auth_key_file: {{ gerrit.get('auth_key_file', '') }}
   - frontendurl: {{ gerrit.get('frontendURL','') }}
+  - build_current_patches_only: {{ gerrit.get('build_current_patches_only', 'false') }}
+  - abort_new_patchsets: {{ gerrit.get('abort_new_patchsets', 'false') }}
+  - abort_manual_patchsets: {{ gerrit.get('abort_manual_patchsets', 'false') }}
+  - abort_same_topic: {{ gerrit.get('abort_same_topic', 'false') }}
   {%- if gerrit.authkey is defined %}
   - authkey: |
       {{ gerrit.get('authkey','')|indent(6) }}
diff --git a/jenkins/files/groovy/gerrit.template b/jenkins/files/groovy/gerrit.template
index 1895494..a6583a1 100644
--- a/jenkins/files/groovy/gerrit.template
+++ b/jenkins/files/groovy/gerrit.template
@@ -1,56 +1,91 @@
 #!groovy
-import jenkins.model.*;
-import net.sf.json.*;
-import com.sonyericsson.hudson.plugins.gerrit.trigger.*;
+import jenkins.model.Jenkins
+import com.sonyericsson.hudson.plugins.gerrit.trigger.GerritServer
+import com.sonyericsson.hudson.plugins.gerrit.trigger.PluginImpl
+import com.sonyericsson.hudson.plugins.gerrit.trigger.VerdictCategory
+import com.sonyericsson.hudson.plugins.gerrit.trigger.config.Config
 
-if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "gerrit-trigger" } != null ) {
-    def gerritPlugin = Jenkins.instance.getPlugin(com.sonyericsson.hudson.plugins.gerrit.trigger.PluginImpl.class)
-    gerritPlugin.getPluginConfig().setNumberOfReceivingWorkerThreads(3)
-    gerritPlugin.getPluginConfig().setNumberOfSendingWorkerThreads(1)
+def authkey = """${authkey}
+"""
+def serverName = "${name}"
 
-    def authkey = """${authkey}
-    """
+def newGerritConfig = new Config()
+newGerritConfig.with {
+setGerritHostName("${hostname}")
+setGerritUserName("${username}")
+setGerritFrontEndURL("${frontendurl}")
+setGerritSshPort(("${port}").toInteger())
+setGerritProxy("${proxy}")
+setGerritEMail("${email}")
+buildCurrentPatchesOnly.setEnabled(("${build_current_patches_only}").toBoolean())
+buildCurrentPatchesOnly.setAbortNewPatchsets(("${abort_new_patchsets}").toBoolean())
+buildCurrentPatchesOnly.setAbortManualPatchsets(("${abort_manual_patchsets}").toBoolean())
+buildCurrentPatchesOnly.setAbortSameTopic(("${abort_same_topic}").toBoolean())
+setGerritAuthKeyFilePassword("${auth_key_file_password}")
+}
 
-    def serverName = "${name}"
-    def gerritServer = new GerritServer(serverName)
+def gerritAuthKeyFile = new File("${auth_key_file}")
+gerritAuthKeyFile.write(authkey)
+if ( gerritAuthKeyFile.exists() ) {
+     newGerritConfig.setGerritAuthKeyFile(gerritAuthKeyFile)
+}
 
+def newCategories = newGerritConfig.getCategories()
+if (!newCategories) {
+    categories = new LinkedList<VerdictCategory>()
+}
+if (newCategories.isEmpty()) {
+    newCategories.add(new VerdictCategory('Code-Review', 'Code Review'))
+    newCategories.add(new VerdictCategory('Verified', 'Verified'))
+}
+
+Boolean compareObjects( Object a, b) {
+    String aXML = Jenkins.XSTREAM.toXML(a).replaceAll(/\{AQA[^\}]+\}/) {
+                      hudson.util.Secret.decrypt(it) }
+    String bXML = Jenkins.XSTREAM.toXML(b).replaceAll(/\{AQA[^\}]+\}/) {
+                      hudson.util.Secret.decrypt(it) }
+    return aXML == bXML
+}
+
+if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == 'gerrit-trigger' } != null ) {
+    def gerritPlugin = Jenkins.instance.getPlugin(PluginImpl)
     def gerritTriggerPlugin = PluginImpl.getInstance()
     def gerritServers = gerritTriggerPlugin.getServerNames()
+
+    def gerritServer = gerritPlugin.getServer(serverName)
+    def newGerritServer = new GerritServer(serverName)
+
+    newGerritConfig.setCategories(newCategories)
+
     def gerritServerExists = false
     gerritServers.each {
         serverName = (String) it
-        if ( serverName == gerritServer.getName() ) {
+        if ( serverName == newGerritServer.getName() ) {
             gerritServerExists = true
         }
     }
-    if (!gerritServerExists){
 
-        def triggerConfig = new config.Config()
+    newGerritServer.setConfig(newGerritConfig)
 
-        triggerConfig.setGerritHostName("${hostname}")
-        triggerConfig.setGerritUserName("${username}")
-        triggerConfig.setGerritFrontEndURL("${frontendurl}")
-        triggerConfig.setGerritSshPort(${port})
-        triggerConfig.setGerritProxy("${proxy}")
-        triggerConfig.setGerritEMail("${email}")
-
-        def gerritAuthKeyFile = new File("${auth_key_file}")
-        gerritAuthKeyFile.write(authkey)
-        if ( gerritAuthKeyFile.exists() ) {
-            triggerConfig.setGerritAuthKeyFile(gerritAuthKeyFile)
+    if (gerritServerExists){
+        if (compareObjects(gerritServer, newGerritServer)) {
+            print('SKIPPED')
+        } else {
+            if (gerritServer) {
+                gerritServer.setConfig(newGerritServer.getConfig())
+            } else {
+                gerritPlugin.addServer(newGerritServer)
+            }
+            newGerritServer.start()
+            newGerritServer.startConnection()
+            Jenkins.instance.save()
+            print('CHANGED')
         }
-
-        triggerConfig.setGerritAuthKeyFilePassword("${auth_key_file_password}")
-
-        gerritServer.setConfig(triggerConfig)
-
-        gerritPlugin.addServer(gerritServer)
-        gerritServer.start()
-        gerritServer.startConnection()
+    } else {
+        gerritPlugin.addServer(newGerritServer)
+        print('CREATED')
+        newGerritServer.start()
+        newGerritServer.startConnection()
         Jenkins.instance.save()
-        print("CREATED")
-    }
-    else {
-        print("EXISTS")
     }
 }