/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ "use strict"; var __rt=require('streamline/lib/callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb,__catch=__rt.__catch,__tryCatch=__rt.__tryCatch,__forIn=__rt.__forIn; var streams = require("streamline/lib/streams/streams");

















var util = require("util");

var profile = require("../../../util/profile");
var utils = require("../../../util/utils");

var groupUtils = require("./groupUtils");
var permissionsUtils = require("../role/permissionsUtils");
var rbacClients = require("../role/rbacClients");
var resourceUtils = require("../resource/resourceUtils");
var tagUtils = require("../tag/tagUtils");
var fs = require("fs");
var path = require("path");

var $ = utils.getLocaleString;

exports.init = function(cli) {
  var log = cli.output;

  var group = cli.category("group").description($("Commands to manage your resource groups"));


  group.command("create [name] [location]").description($("Creates a new resource group")).usage("[options] <name> <location>").option("-n --name <name>", $("the resource group name")).option("-l --location <location>", $("the location where we will create the group")).option("-d --deployment-name <deployment-name>", $("the name of the deployment we will create (only valid when a template is used)")).fileRelatedOption("-f --template-file <template-file>", $("the path to the template file in the file system")).option("--template-uri <template-uri>", $("the uri to the remote template file")).option("--template-version <template-version>", $("the content version of the template")).option("-p --parameters <parameters>", $("a JSON-formatted string containing parameters")).fileRelatedOption("-e --parameters-file <parametersFile>", $("a file containing parameters")).option("-t --tags <tags>", $(("Tags to set to the resource group. Can be multiple. " + "In the format of 'name=value'. Name is required and value is optional. For example, -t tag1=value1;tag2"))).option("--subscription <subscription>", $("the subscription identifier")).execute(function __1(name, location, options, _) { var updatedGroup; var __frame = { name: "__1", line: 54 }; return __func(_, this, arguments, __1, 3, __frame, function __$__1() {














      if (!name) {
        return _(null, cli.missingArgument("name")); } ;

      if (!location) {
        return _(null, cli.missingArgument("location")); } ;

      return group.createResourceGroup(name, location, options, __cb(_, __frame, 7, 31, function ___(__0, __1) { updatedGroup = __1;
        showResourceGroup(updatedGroup); _(); }, true)); }); });


  group.command("set [name]").description($("Set tags to a resource group")).usage("[options] <name> <tags>").option("-n --name <name>", $("the resource group name")).option("-t --tags <tags>", $(("Tags to set to the resource group. Can be multiple. " + "In the format of 'name=value'. Name is required and value is optional. For example, -t tag1=value1;tag2"))).option("--no-tags", $("remove all existing tags")).option("--subscription <subscription>", $("the subscription identifier")).execute(function __2(name, options, _) { var updatedGroup; var __frame = { name: "__2", line: 73 }; return __func(_, this, arguments, __2, 2, __frame, function __$__2() {








      if (!name) {
        return _(null, cli.missingArgument("name")); } ;

      return group.createResourceGroup(name, "", options, __cb(_, __frame, 4, 31, function ___(__0, __1) { updatedGroup = __1;
        showResourceGroup(updatedGroup); _(); }, true)); }); });


  group.createResourceGroup = function group_createResourceGroup__3(name, location, options, _) { var subscription, client, existingGroup, message, doneMessage, tags, group; var __frame = { name: "group_createResourceGroup__3", line: 81 }; return __func(_, this, arguments, group_createResourceGroup__3, 3, __frame, function __$group_createResourceGroup__3() {
      subscription = profile.current.getSubscription(options.subscription);
      client = utils.createResourceClient(subscription);



      return cli.interaction.withProgress(util.format($("Getting resource group %s"), name), function __1(log, _) { var __frame = { name: "__1", line: 88 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {

          return groupUtils.getGroup(client, name, __cb(_, __frame, 1, 35, function ___(__0, __1) { existingGroup = __1; _(); }, true)); }); }, __cb(_, __frame, 6, 20, function __$group_createResourceGroup__3() {


        if (!location) {
          if (existingGroup) {
            location = existingGroup.location; }

           else {
            return _(new Error(("Please provide a location to create a resource group. " + "You can run 'azure location list' to get the list of valid locations for resource group."))); } ; } ;




        message = util.format($("Creating resource group %s"), name);
        doneMessage = util.format($("Created resource group %s"), name);
        if (existingGroup) {
          message = util.format($("Updating resource group %s"), name);
          doneMessage = util.format($("Updated resource group %s"), name); } ;


        tags = (((existingGroup && existingGroup.tags)) || { });
        tags = tagUtils.buildTagsParameter(tags, options);


        return cli.interaction.withProgress(message, function __2(log, _) { var __frame = { name: "__2", line: 114 }; return __func(_, this, arguments, __2, 1, __frame, function __$__2() { return (function __$__2(__then) {

              if (!existingGroup) {
                return client.resourceGroups.createOrUpdate(name, {
                  location: location,
                  tags: tags }, __cb(_, __frame, 2, 40, function ___(__0, __1) { group = __1; __then(); }, true)); } else {


                return client.resourceGroups.patch(name, {
                  location: location,
                  tags: tags }, __cb(_, __frame, 7, 40, function ___(__0, __2) { group = __2; __then(); }, true)); } ; })(_); }); }, __cb(_, __frame, 32, 20, function __$group_createResourceGroup__3() {





          log.info(doneMessage); return (function __$group_createResourceGroup__3(__then) {

            if (((options.templateFile || options.templateUri) || options.deploymentName)) {
              return groupUtils.createDeployment(cli, name, options.deploymentName, options, __cb(_, __frame, 51, 17, __then, true)); } else { __then(); } ; })(function __$group_createResourceGroup__3() {


            return _(null, group); }); }, true)); }, true)); }); };


  group.command("delete [name]").description($("Deletes a resource group")).usage("[options] <name>").option("-n --name <name>", $("the resource group name")).option("--nowait", $("does not wait for the delete operation to complete. Returns as soon as the intial request is received by the server.")).option("-q, --quiet", $("quiet mode (do not ask for delete confirmation)")).option("--subscription <subscription>", $("the subscription identifier")).execute(function __4(name, options, _) { var subscription, client, progress; var __frame = { name: "__4", line: 145 }; return __func(_, this, arguments, __4, 2, __frame, function __$__4() {







      if (!name) {
        return _(null, cli.missingArgument("name")); } ; return (function __$__4(_) {

        var __1 = !options.quiet; if (!__1) { return _(null, __1); } ; return cli.interaction.confirm(util.format($("Delete resource group %s? [y/n] "), name), __cb(_, __frame, 4, 45, function ___(__0, __3) { var __2 = !__3; return _(null, __2); }, true)); })(__cb(_, __frame, -144, 17, function ___(__0, __2) { return (function __$__4(__then) { if (__2) { return _(null); } else { __then(); } ; })(function __$__4() {



          subscription = profile.current.getSubscription(options.subscription);
          client = utils.createResourceClient(subscription);
          progress = cli.interaction.progress(util.format($("Deleting resource group %s"), name)); return (function __$__4(__then) {
            if (options.nowait) { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__4() {

                    return client.resourceGroups.beginDeleteMethod(name, __cb(_, __frame, 13, 32, function __$__4() { _(null, null, true); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$__4() {

                      progress.end(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, __then); }); } else { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__4() {



                    return client.resourceGroups.deleteMethod(name, __cb(_, __frame, 19, 32, function __$__4() { _(null, null, true); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$__4() {

                      progress.end(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, __then); }); } ; })(_); }); }, true)); }); });




  group.command("list").description($("Lists the resource groups for your subscription")).option("-d, --details", $("show additional resource group details such as resources, permissions etc.")).option("-t --tags <tags>", $((("Tag to use to filter to the resource group. Can only take 1 tag. " + "In the format of \"name=value\". Name is required and value is optional. ") + "For example, -t tag1 or -t tag1=value1."))).option("--subscription <subscription>", $("the subscription identifier")).execute(function __5(options, _) { var subscription, client, progress, resourceGroups, parameters, response, authzClient, i, resourceGroup; var __frame = { name: "__5", line: 178 }; return __func(_, this, arguments, __5, 1, __frame, function __$__5() {







      subscription = profile.current.getSubscription(options.subscription);
      client = utils.createResourceClient(subscription);
      progress = cli.interaction.progress($("Listing resource groups"));

      parameters = { };

      if (options.tags) {
        tagUtils.populateQueryFilterWithTagInfo(options.tags, parameters); } ; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__5() {



            return client.resourceGroups.list(parameters, __cb(_, __frame, 12, 45, function ___(__0, __3) { response = __3;
              resourceGroups = response; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$__5() { __more = false;

                  var __8 = response.nextLink; if (__8) {
                    return client.resourceGroups.listNext(response.nextLink, __cb(_, __frame, 16, 43, function ___(__0, __4) { response = __4;
                      resourceGroups.concat(response); while (__more) { __loop(); }; __more = true; }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$__5() { _(null, null, true); }); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$__5() {


              progress.end(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$__5() {



          if (parameters.tagName) {
            resourceGroups = resourceGroups.filter(function(element) {
              return ((element.tags && (element.tags.hasOwnProperty(parameters.tagName))) && ((!parameters.tagValue || (parameters.tagValue === element.tags[parameters.tagName])))); }); } ; return (function __$__5(__then) {




            if (options.details) {
              progress = cli.interaction.progress($("Listing resources for the groups")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__5() {

                    authzClient = rbacClients.getAuthzClient(subscription);
                    var __1 = __forIn(resourceGroups); var __2 = 0; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$__5() { __more = false; var __10 = (__2 < __1.length); if (__10) { i = __1[__2++];
                          resourceGroup = resourceGroups[i];
                          return client.resources.list({ resourceGroupName: resourceGroup.name }, __cb(_, __frame, 37, 55, function ___(__0, __5) { resourceGroup.resources = __5;
                            return authzClient.permissions.listForResourceGroup(resourceGroup.name, __cb(_, __frame, 38, 64, function ___(__0, __6) { resourceGroup.permissions = __6.permissions; while (__more) { __loop(); }; __more = true; }, true)); }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$__5() { _(null, null, true); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$__5() {


                      progress.end(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, __then); }); } else { __then(); } ; })(function __$__5() {



            if (options.details) {
              resourceGroups.forEach(function(rg) {
                formatResourcesForOutput(rg); }); } ;



            cli.interaction.formatOutput(resourceGroups, function(data) {
              if ((data.length === 0)) {
                log.info($("No matched resource groups were found")); }
               else {
                if (options.details) {
                  data.forEach(function(rg) {
                    showResourceGroup(rg, true);
                    log.data($("")); }); }

                 else {
                  log.table(data, function(row, group) {
                    row.cell($("Name"), group.name);
                    row.cell($("Location"), group.location);
                    row.cell($("Provisioning State"), group.properties.provisioningState);
                    row.cell($("Tags:"), tagUtils.getTagsInfo(group.tags)); }); } ; } ; }); _(); }); }); }); }); });






  group.command("show [name]").description($("Shows a resource group for your subscription")).usage("[options] <name>").option("-n --name <name>", $("the resource group name")).option("--subscription <subscription>", $("the subscription identifier")).execute(function __6(name, options, _) { var subscription, client, authzClient, progress, resourceGroup; var __frame = { name: "__6", line: 255 }; return __func(_, this, arguments, __6, 2, __frame, function __$__6() {





      if (!name) {
        return _(null, cli.missingArgument("name")); } ;

      subscription = profile.current.getSubscription(options.subscription);
      client = utils.createResourceClient(subscription);
      authzClient = rbacClients.getAuthzClient(subscription);

      progress = cli.interaction.progress($("Listing resource groups")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__6() {


            return client.resourceGroups.get(name, __cb(_, __frame, 11, 46, function ___(__0, __1) { resourceGroup = __1; _(null, null, true); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$__6() {

              progress.end(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$__6() {



          progress = cli.interaction.progress($("Listing resources for the group")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__6() {

                return client.resourceGroups.listResources(name, __cb(_, __frame, 19, 56, function ___(__0, __2) { resourceGroup.resources = __2;
                  return authzClient.permissions.listForResourceGroup(name, __cb(_, __frame, 20, 60, function ___(__0, __3) { resourceGroup.permissions = __3.permissions; _(null, null, true); }, true)); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$__6() {

                  progress.end(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$__6() {


              formatResourcesForOutput(resourceGroup);
              cli.interaction.formatOutput(resourceGroup, function(outputData) {
                showResourceGroup(outputData, true); }); _(); }); }); }); }); }); });



  group.command("export [name] [directory]").description($("Captures a resource group as a template, and saves it as file on disk.")).usage("[options] <name> [directory]").option("-n --name <name>", $("the resource group name")).option("-d --directory [directory]", $("the name of the destination directory. If not specified, template file will be saved in the current directory.")).option("-c --includeComments", $("export template with comments.")).option("-p --includeParameterDefaultValue", $("export template parameter with default value")).option("-q --quiet", $("quiet mode (do not prompt for overwrite if output file exists)")).option("--subscription <subscription>", $("the subscription identifier")).execute(function __7(name, directory, options, _) { var subscription, client, confirm, result, template, error, fileName; var __frame = { name: "__7", line: 295 }; return __func(_, this, arguments, __7, 3, __frame, function __$__7() {









      if (!name) {
        return _(null, cli.missingArgument("name")); } ;


      subscription = profile.current.getSubscription(options.subscription);
      client = utils.createResourceClient(subscription); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__7() {

            return client.resourceGroups.checkExistence(name, __cb(_, __frame, 8, 28, __then, true)); }); })(function ___(err, __result) { __catch(function __$__7() { if (err) {


              return _(new Error(util.format($("Resource group %s does not exist."), name))); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$__7() {


          confirm = cli.interaction.confirm.bind(cli.interaction);
          return cli.interaction.withProgress(util.format($("Exporting resource group as template %s"), name), function __1(log, _) { var exportOptions, parameters; var __frame = { name: "__1", line: 312 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {



              if (options.includeComments) {
                exportOptions = "IncludeComments"; } ;

              if (options.includeParameterDefaultValue) {
                if (!utils.stringIsNullOrEmpty(exportOptions)) {
                  exportOptions += ", IncludeParameterDefaultValue"; }

                 else {
                  exportOptions = "IncludeParameterDefaultValue"; } ; } ;


              parameters = {
                resources: ["*",] };

              if (!utils.stringIsNullOrEmpty(exportOptions)) {
                parameters.options = exportOptions; } ;

              return client.resourceGroups.exportTemplate(name, parameters, __cb(_, __frame, 19, 37, _, true)); }); }, __cb(_, __frame, 15, 33, function ___(__0, __2) { result = __2;


            template = result.template;


            error = result.error;
            if (error) {
              log.warn(util.format($("%s : %s"), error.code, error.message));
              if (error.details) {
                error.details.forEach(function(detail) {
                  log.warn(util.format($("%s : %s"), detail.code, detail.message)); }); } ; } ;




            fileName = (directory ? path.join(directory, (name + ".json")) : path.join(process.cwd(), (name + ".json")));
            return groupUtils.normalizeDownloadFileName(fileName, options.quiet, confirm, __cb(_, __frame, 53, 26, function ___(__0, __3) { fileName = __3;
              if (fileName) {
                fs.writeFileSync(fileName, JSON.stringify(template, null, 2));
                log.info(util.format($("Template downloaded to %s"), fileName)); } ; _(); }, true)); }, true)); }); }); }); });




  function formatResourcesForOutput(resourceGroup) {
    if ((resourceGroup.resources && (resourceGroup.resources.length > 0))) {
      resourceGroup.resources = resourceGroup.resources.map(function(r) {
        var resourceInformation = resourceUtils.getResourceInformation(r.id);
        var formattedResource = {
          id: r.id,
          name: resourceInformation.resourceName,
          type: resourceUtils.getResourceTypeName(resourceInformation.resourceType),
          location: r.location,
          tags: tagUtils.getTagsInfo(r.tags) };

        return formattedResource; }); } ; };




  function showResourceGroup(resourceGroup, showDetail) {
    cli.interaction.formatOutput(resourceGroup, function(resourceGroup) {
      log.data($("Id:                 "), resourceGroup.id);
      log.data($("Name:               "), resourceGroup.name);
      log.data($("Location:           "), resourceGroup.location);
      log.data($("Provisioning State: "), resourceGroup.properties.provisioningState);
      log.data(util.format($("Tags: %s"), tagUtils.getTagsInfo(resourceGroup.tags)));

      if (showDetail) {
        if ((resourceGroup.resources && (resourceGroup.resources.length > 0))) {
          log.data($("Resources:"));
          log.data($(""));

          for (var i = 0; (i < resourceGroup.resources.length); i++) {
            var item = resourceGroup.resources[i];
            log.data($("  Id      :"), item.id);
            log.data($("  Name    :"), item.name);
            log.data($("  Type    :"), item.type);
            log.data($("  Location:"), item.location);
            log.data($("  Tags    :"), item.tags);
            log.data($("")); }; }

         else {
          log.data($("Resources:  []")); } ;


        if (resourceGroup.permissions) {
          var permissionDetails = permissionsUtils.getPermissionDetails(resourceGroup.permissions);
          log.data($("Permissions:"));
          log.data(($("  Actions: ") + permissionDetails.actions));
          log.data(($("  NotActions: ") + permissionDetails.notActions)); } ; } ;


      log.data(""); }); };



  var grouplog = group.category("log").description($("Commands to manage resource group logs"));


  var logReport = [[$("EventId"),"eventDataId",],[$("Authorization"),"authorization",[["action","action",],["role","role",],["scope","scope",],],],[$("ResourceUri"),"resourceUri",],[$("SubscriptionId"),"subscriptionId",],[$("EventTimestamp (UTC)"),"eventTimestamp",log.report.asDate,],[$("OperationName"),"operationName.localizedValue",],[$("OperationId"),"operationId",],[$("Status"),"status.localizedValue",],[$("SubStatus"),"subStatus.localizedValue",],[$("Caller"),"caller",],[$("CorrelationId"),"correlationId",],[$("Description"),"description",],[$("HttpRequest"),"httpRequest",log.report.allProperties,],[$("Level"),"level",],[$("ResourceGroup"),"resourceGroupName",],[$("ResourceProvider"),"resourceProviderName.localizedValue",],[$("EventSource"),"eventSource.localizedValue",],[$("Properties"),"properties",log.report.allProperties,],];



























  grouplog.command("show [name]").description($("Retrieves and shows logs for resource group operations")).option("-n --name <name>", $("the resource group name")).option("-a --all", $("returns logs for all operations (including CRUD and deployment)")).option("-l --last-deployment", $("returns logs for the last deployment")).option("-d --deployment <name>", $("the name of the deployment whose logs you want to see")).option("-s --subscription <subscription>", $("the subscription identifier")).execute(function __8(name, options, _) { var subscription, progress, logStream, logEntry, isJson, logEntrySet;


















    function endProgress() {
      if (progress) {
        progress.end();
        progress = null; } ; }; var __frame = { name: "__8", line: 447 }; return __func(_, this, arguments, __8, 2, __frame, function __$__8() { if (!name) { return _(null, cli.missingArgument("name")); } ; if (([options.all,options.lastDeployment,options.deployment,].filter(function(opt) { return opt; }).length > 1)) { return _(new Error($("Must specify only one of --all, --last-deployment, or --deployment switches"))); } ; subscription = profile.current.getSubscription(options.subscription); progress = cli.interaction.progress($("Getting group logs"));





      if (options.all) {
        logStream = groupUtils.getAllEvents(subscription, name); } else {
        if (options.deployment) {
          logStream = groupUtils.getDeploymentLog(subscription, name, options.deployment); }
         else {
          logStream = groupUtils.getLastDeploymentLog(subscription, name); } ; } ;


      logStream = new streams.ReadableStream(logStream);

      return logStream.read(__cb(_, __frame, 31, 31, function ___(__0, __1) { logEntry = __1;
        endProgress();

        isJson = cli.output.format().json;
        logEntrySet = []; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$__8() { __more = false;

            var __4 = (logEntry !== null); if (__4) {
              if (isJson) {
                logEntrySet.push(logEntry); }
               else {
                log.data("----------");
                log.report(logReport, logEntry); } ;

              return logStream.read(__cb(_, __frame, 44, 29, function ___(__0, __2) { logEntry = __2; while (__more) { __loop(); }; __more = true; }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$__8() {


          if ((isJson && (logEntrySet.length > 0))) {
            cli.output.json(logEntrySet); } ; _(); }); }, true)); }); });};
