var appPrefix = 'x_xma_xmatters';
var json = new global.JSON();

//Get the credentials for xMatters
var pass = '';
pass = gs.getProperty(appPrefix + '.' + 'xmatters.reb.password');
var user = '';
user = gs.getProperty(appPrefix + '.' + 'xmatters.reb.user');

//Grab the endpoint system properties to set correct endpoints for xm
var xm_endpoint = '';
xm_endpoint = gs.getProperty(appPrefix + '.' + 'xmatters.reb.hostname');
gs.info("xMatters Endpoint is: " + xm_endpoint);
gs.info("Logging into xMatters with: " + user);

//Perform query on groups with xmatters role
var groups = new GlideRecord('sys_user_group');
groups.addQuery('roles','x_xma_xmatters.xmatters');
groups.addActiveQuery();
groups.query();

//Create a list of groups to be synced with external key
var list2 = [];

while(groups.next()){
 list2.push(groups.getValue('name'));
}

//For each group in the list, perform a get to get their current payload for REST
list2.forEach(function(rest2) {
 restMessage3 = new sn_ws.RESTMessageV2();
 this.restMessage3.setBasicAuth(user,pass);
 this.restMessage3.setHttpMethod('get');
 this.restMessage3.setRequestHeader('Content-Type','application/json');
 this.restMessage3.setEndpoint(xm_endpoint + "/api/xm/1/groups/" + (encodeURIComponent(rest2)));
 gs.info("Sending REST GET for group to grab Info: " + rest2);
 response3 = restMessage3.execute();
 responseBody3 = response3.getBody();
 resp3 = responseBody3;
 var resp4 = JSON.parse(resp3);

 gs.info("Old key = " + resp4.externalKey + " owned: " + resp4.externallyOwned);
 //If any group does not have a externallyOwned, set
 if (!resp4.externallyOwned || resp4.externalKey != rest2) {
 
  gs.info("Updating key");
  resp4.externallyOwned = true;
  resp4.externalKey = resp4.targetName;
  resp3 = JSON.stringify(resp4);
 
  gs.info("New response body to send to xM with externallyOwned:" + resp4.targetName);
 
  restMessage4 = new sn_ws.RESTMessageV2();
  this.restMessage4.setBasicAuth(user,pass);
  this.restMessage4.setHttpMethod('post');
  this.restMessage4.setRequestHeader('Content-Type','application/json');
  this.restMessage4.setEndpoint(xm_endpoint + "/api/xm/1/groups/");
  this.restMessage4.setRequestBody(resp3);
  gs.info("Sending REST POST for group" + resp3);
  response4 = restMessage4.execute();
  responseBody4 = response4.getBody();
  gs.info("Response: " + responseBody4);
 }
});