/*** 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; var __ = require("underscore");

















var util = require("util");

var adUtils = require("../ad/adUtils");
var groupUtils = require("../group/groupUtils");
var profile = require("../../../util/profile");
var resourceUtils = require("../resource/resourceUtils");
var utils = require("../../../util/utils");
var kvUtils = require("./kv-utils");

var $ = utils.getLocaleString;

var API_VERSION = "2015-06-01";
var RESOURCE_TYPE = "Microsoft.KeyVault/vaults";
var SKU_TYPE = ["Standard","Premium",];
var KEY_PERMS = ["all","create","import","update","delete","get","list","backup","restore","sign","verify","encrypt","decrypt","wrapKey","unwrapKey",];
var SECRET_PERMS = ["all","set","get","list","delete",];

exports.init = function(cli) {

  var log = cli.output;
  var withProgress = cli.interaction.withProgress.bind(cli.interaction);
  var graphClient;

  var vault = cli.category("keyvault").description($("Commands to manage key vault instances in the Azure Key Vault service"));


  vault.command("list [resource-group]").description($("Lists existing vaults")).usage("[[--resource-group] <resource-group>] [options]").option("-g, --resource-group <resource-group>", $("lists only vaults belonging to the informed resource group")).option("-s, --subscription <subscription>", $("the subscription identifier")).execute(function __1(resourceGroup, options, _) { var subscription, client, resources, progress, parameters, i; var __frame = { name: "__1", line: 54 }; return __func(_, this, arguments, __1, 2, __frame, function __$__1() {














      log.verbose(("arguments: " + JSON.stringify({
        resourceGroup: resourceGroup,
        options: options })));


      options.resourceGroup = (options.resourceGroup || resourceGroup);

      if (options.tags) {

        return _(new Error("Not implemented")); } ;






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


      progress = cli.interaction.progress($("Listing vaults"));
      parameters = { }; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__1() {

            parameters.filter = (("resourceType eq '" + RESOURCE_TYPE) + "'"); return (function __$__1(__then) {
              if (options.resourceGroup) {
                return client.resourceGroups.listResources(options.resourceGroup, parameters, __cb(_, __frame, 31, 44, function ___(__0, __1) { resources = __1; __then(); }, true)); } else {

                return client.resources.list(parameters, __cb(_, __frame, 33, 39, function ___(__0, __2) { resources = __2; __then(); }, true)); } ; })(function __$__1() {

              for (i = 0; (i < resources.length); ++i) {
                resources[i].resourceGroup = resourceUtils.getResourceInformation(resources[i].id); }; _(null, null, true); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$__1() {


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





          if ((resources.length === 0)) {
            log.info($("No vaults found.")); }
           else {
            log.table(resources, function(row, item) {
              row.cell($("Name"), item.name);
              row.cell($("Resource Group"), item.resourceGroup.resourceGroup);
              row.cell($("Location"), item.location);
              row.cell($("Tags"), kvUtils.getTagsInfo(item.tags)); }); } ; _(); }); }); }); });




  vault.command("create [vault-name]").description($("Creates a vault")).usage("[--vault-name] <vault-name> --resource-group <resource-group> --location <location> [options]").option("-u, --vault-name <vault-name>", $("the vault name; this is used to compute the vault's DNS name")).option("-g, --resource-group <resource-group>", $("the resource group name")).option("-l, --location <location>", $("Azure region in which to create the vault")).option("-x, --sku <sku>", util.format($("SKU setting, one of: [%s]"), SKU_TYPE.join(", "))).option("-t, --tags <tags>", $("Tags to set on the vault. Can be multiple in the format 'name=value'. Name is required and value is optional. For example, -t tag1=value1;tag2")).option("-s, --subscription <subscription>", $("The subscription identifier")).option("--no-self-perms", $("If specified, don't add permissions for the current user in the new vault")).execute(function __2(vaultName, options, _) { var subscription, client, identity, vaultResource, properties, objectId, request; var __frame = { name: "__2", line: 121 }; return __func(_, this, arguments, __2, 2, __frame, function __$__2() {















      log.verbose(("arguments: " + JSON.stringify({
        vaultName: vaultName,
        options: options })));


      options.vaultName = (options.vaultName || vaultName);

      if (!options.vaultName) {
        return _(null, cli.missingArgument("vault-name")); } else {
        if (!options.resourceGroup) {
          return _(null, cli.missingArgument("resource-group")); } else {
          if (!options.location) {
            return _(null, cli.missingArgument("location")); } ; } ; } ;


      options.sku = kvUtils.parseEnumArgument("sku", options.sku, SKU_TYPE, SKU_TYPE[0]);
      options.tags = kvUtils.parseTagsArgument("tags", options.tags);





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





      identity = createVaultIdentity(options.vaultName);

      return withProgress($("Checking pre-condition"), function __1(log, _) { var resourceGroup; var __frame = { name: "__1", line: 159 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {

          return getVaultResourceGroup(client, options.vaultName, __cb(_, __frame, 1, 30, function ___(__0, __1) { resourceGroup = __1;
            if (!resourceGroup) {
              return _(null, null); } ;

            return groupUtils.getResource(client, resourceGroup, identity, __cb(_, __frame, 5, 28, _, true)); }, true)); }); }, __cb(_, __frame, 37, 26, function ___(__0, __3) { vaultResource = __3;


        if (vaultResource) {
          return _(new Error(util.format($("Vault %s already exists"), (vaultResource.name || options.vaultName)))); } ;






        properties = {
          sku: {
            family: "A",
            name: options.sku },

          tenantId: subscription.tenantId,
          accessPolicies: [] }; return (function __$__2(__then) {


          if (!options.selfPerms) {

            log.verbose($("Flag --no-self-perms found, skipping add permissions...")); __then(); } else { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__2() {





                  log.verbose($("Attempting to get authenticated user information from directory..."));
                  return getCurrentUserObjectId(__cb(_, __frame, 72, 21, function ___(__0, __4) { objectId = __4; __then(); }, true)); }); })(function ___(e, __result) { __catch(function __$__2() { if (e) {

                    log.verbose(JSON.stringify(e, null, " "));
                    log.warn($("Unable to get authenticated user information. Increase verbosity to get more information.")); __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$__2() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__2() { return (function __$__2(__then) {



                        if (!objectId) {
                          log.verbose($("Attempting to lookup current user in directory..."));
                          return getObjectId(subscription, null, null, __cb(_, __frame, 81, 23, function ___(__0, __5) { objectId = __5; __then(); }, true)); } else { __then(); } ; })(__then); }); })(function ___(e, __result) { __catch(function __$__2() { if (e) {


                        log.verbose(JSON.stringify(e, null, " "));
                        log.warn($("Unable to lookup current user. Increase verbosity to get more information.")); __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$__2() {


                    if (!objectId) {
                      log.error($("Unable to query active directory for information about the current user."));
                      log.error($("You may try the --no-self-perms flag to create a vault without permissions."));
                      return _(new Error("Cannot create vault. See previous messages.")); } ;


                    properties.accessPolicies = [{

                      tenantId: subscription.tenantId,
                      objectId: objectId,
                      permissions: {

                        keys: ["get","create","delete","list","update","import","backup","restore",],

                        secrets: ["all",] } },]; __then(); }); }); }); }); } ; })(function __$__2() {





          request = {
            location: options.location,
            properties: properties,
            tags: options.tags };


          log.verbose(("request: " + JSON.stringify(request)));

          return withProgress(util.format($("Creating vault %s"), options.vaultName), function __2(log, _) { var __frame = { name: "__2", line: 238 }; return __func(_, this, arguments, __2, 1, __frame, function __$__2() {

              return client.resources.createOrUpdate(options.resourceGroup, identity.resourceProviderNamespace, identity.parentResourcePath, identity.resourceType, identity.resourceName, identity.resourceProviderApiVersion, request, __cb(_, __frame, 1, 34, _, true)); }); }, __cb(_, __frame, 116, 22, function ___(__0, __6) { vaultResource = __6;









            log.info(util.format($("Created vault %s"), (vaultResource.name || options.vaultName)));
            return showVault(vaultResource, __cb(_, __frame, 129, 6, function __$__2() {

              if (((!vaultResource.properties || !vaultResource.properties.accessPolicies) || !vaultResource.properties.accessPolicies.length)) {
                log.warn($("This vault has no permissions. It's not unusable until permissions are explicitly set."));
                log.warn($("You can use 'azure keyvault set-policy' anytime to set permissions.")); } ;


              if (utils.ignoreCaseEquals(properties.sku.name, "standard")) {
                log.warn("This vault does not support HSM-protected keys. Please refer to http://go.microsoft.com/fwlink/?linkid=512521 for the vault service tiers.");
                log.warn("When creating a vault, specify the --sku parameter to select a service tier that supports HSM-protected keys."); } ; _(); }, true)); }, true)); }); }, true)); }); });




  vault.command("set-attributes [vault-name]").description($("Changes attributes of an existing vault")).usage("[--vault-name] <vault-name> [options]").option("-u, --vault-name <vault-name>", $("the vault name")).option("-g, --resource-group <resource-group>", $("changes only if vault belongs to the informed resource group; otherwise returns 'not found'")).option("-x, --sku <sku>", util.format($("SKU setting, one of: [%s]"), SKU_TYPE.join(", "))).option("-t, --tags <tags>", $("Tags to set on the vault. Can be multiple in the format 'name=value'. Name is required and value is optional. For example, -t tag1=value1;tag2")).option("--reset-tags", $("remove previously existing tags; can combined with --tags")).option("-s, --subscription <subscription>", $("the subscription identifier")).execute(function __3(vaultName, options, _) { var subscription, client, identity, resourceGroup, vaultResource, properties, request; var __frame = { name: "__3", line: 273 }; return __func(_, this, arguments, __3, 2, __frame, function __$__3() {














      log.verbose(("arguments: " + JSON.stringify({
        vaultName: vaultName,
        options: options })));


      options.vaultName = (options.vaultName || vaultName);

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






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





      identity = createVaultIdentity(options.vaultName);


      return withProgress(util.format($("Loading vault %s"), options.vaultName), function __1(log, _) { var __frame = { name: "__1", line: 305 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() { return (function __$__1(_) {

            var __1 = options.resourceGroup; if (__1) { return _(null, __1); } ; return getVaultResourceGroup(client, options.vaultName, __cb(_, __frame, 1, 51, _, true)); })(__cb(_, __frame, -304, 17, function ___(__0, __2) { resourceGroup = __2;
            if (!resourceGroup) {
              return _(null, null); } ;

            return groupUtils.getResource(client, resourceGroup, identity, __cb(_, __frame, 5, 28, _, true)); }, true)); }); }, __cb(_, __frame, 31, 26, function ___(__0, __3) { vaultResource = __3;


        if (!vaultResource) {
          return _(notFoundError(options.resourceGroup, options.vaultName)); } ;


        options.vaultName = (vaultResource.name || options.vaultName);

        properties = vaultResource.properties;





        options.sku = kvUtils.parseEnumArgument("sku", options.sku, SKU_TYPE, properties.sku.name);

        options.tags = kvUtils.parseTagsArgument("tags", options.tags);
        if (options.tags) {
          if (!options.resetTags) {
            options.tags = kvUtils.mergeTags(vaultResource.tags, options.tags); } ; } else {

          if (options.resetTags) {
            options.tags = { }; } ; } ;






        properties.sku.name = options.sku;

        request = {
          location: vaultResource.location,
          properties: vaultResource.properties,
          tags: options.tags };


        log.verbose(("request: " + JSON.stringify(request)));

        return withProgress(util.format($("Updating vault %s"), options.vaultName), function __2(log, _) { var __frame = { name: "__2", line: 351 }; return __func(_, this, arguments, __2, 1, __frame, function __$__2() {

            return client.resources.createOrUpdate(resourceGroup, identity.resourceProviderNamespace, identity.parentResourcePath, identity.resourceType, identity.resourceName, identity.resourceProviderApiVersion, request, __cb(_, __frame, 1, 34, _, true)); }); }, __cb(_, __frame, 77, 22, function ___(__0, __4) { vaultResource = __4;









          log.info(util.format($("Vault %s was updated"), vaultName));
          return showVault(vaultResource, __cb(_, __frame, 90, 6, function __$__3() { _(); }, true)); }, true)); }, true)); }); });


  vault.command("show [vault-name]").description($("Shows properties of a vault")).usage("[--vault-name] <vault-name> [options]").option("-u, --vault-name <vault-name>", $("the vault name")).option("-g, --resource-group <resource-group>", $("shows only if vault belongs to the informed resource group; otherwise returns 'not found'")).option("-s, --subscription <subscription>", $("the subscription identifier")).execute(function __4(vaultName, options, _) { var subscription, client, identity, resourceGroup, vaultResource; var __frame = { name: "__4", line: 372 }; return __func(_, this, arguments, __4, 2, __frame, function __$__4() {











      log.verbose(("arguments: " + JSON.stringify({
        vaultName: vaultName,
        options: options })));


      options.vaultName = (options.vaultName || vaultName);

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






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





      identity = createVaultIdentity(options.vaultName);


      return withProgress(util.format($("Loading vault %s"), options.vaultName), function __1(log, _) { var __frame = { name: "__1", line: 404 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() { return (function __$__1(_) {

            var __1 = options.resourceGroup; if (__1) { return _(null, __1); } ; return getVaultResourceGroup(client, options.vaultName, __cb(_, __frame, 1, 51, _, true)); })(__cb(_, __frame, -403, 17, function ___(__0, __2) { resourceGroup = __2;
            if (!resourceGroup) {
              return _(null, null); } ;

            return groupUtils.getResource(client, resourceGroup, identity, __cb(_, __frame, 5, 28, _, true)); }, true)); }); }, __cb(_, __frame, 31, 26, function ___(__0, __2) { vaultResource = __2;



        if (!vaultResource) {
          return _(notFoundError(options.resourceGroup, options.vaultName)); } ;


        return showVault(vaultResource, __cb(_, __frame, 45, 6, function __$__4() { _(); }, true)); }, true)); }); });


  vault.command("delete [vault-name]").description($("Deletes an existing vault")).usage("[--vault-name] <vault-name> [options]").option("-u, --vault-name <vault-name>", $("the vault name")).option("-g, --resource-group <resource-group>", $("deletes only if vault belongs to the informed resource group; otherwise returns 'not found'")).option("-q, --quiet", $("quiet mode (do not ask for delete confirmation)")).option("-p, --pass-thru", $("outputs the deleted vault")).option("-s, --subscription <subscription>", $("the subscription identifier")).execute(function __5(vaultName, options, _) { var subscription, client, identity, progress, resourceGroup; var __frame = { name: "__5", line: 428 }; return __func(_, this, arguments, __5, 2, __frame, function __$__5() {













      log.verbose(("arguments: " + JSON.stringify({
        vaultName: vaultName,
        options: options })));


      options.vaultName = (options.vaultName || vaultName);

      if (!options.vaultName) {
        return _(null, cli.missingArgument("vault-name")); } ; return (function __$__5(_) {


        var __1 = !options.quiet; if (!__1) { return _(null, __1); } ; return cli.interaction.confirm(util.format($("Delete vault %s? [y/n] "), options.vaultName), __cb(_, __frame, 17, 45, function ___(__0, __3) { var __2 = !__3; return _(null, __2); }, true)); })(__cb(_, __frame, -427, 17, function ___(__0, __3) { return (function __$__5(__then) { if (__3) {
            return _(new Error($("Aborted by user"))); } else { __then(); } ; })(function __$__5() {






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





          identity = createVaultIdentity(options.vaultName);

          progress = cli.interaction.progress(util.format($("Deleting vault %s"), options.vaultName)); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__5() { return (function __$__5(_) {

                  var __2 = options.resourceGroup; if (__2) { return _(null, __2); } ; return getVaultResourceGroup(client, options.vaultName, __cb(_, __frame, 36, 53, _, true)); })(__cb(_, __frame, -427, 17, function ___(__0, __4) { resourceGroup = __4;
                  if (!resourceGroup) {
                    return _(notFoundError(options.resourceGroup, options.vaultName)); } ;

                  return client.resources.deleteMethod(resourceGroup, identity.resourceProviderNamespace, identity.parentResourcePath, identity.resourceType, identity.resourceName, identity.resourceProviderApiVersion, __cb(_, __frame, 40, 25, function __$__5() { _(null, null, true); }, 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() { _(); }); }); }); }, true)); }); });




  vault.command("set-policy [vault-name]").description($("Adds or modifies an access policy for a vault")).usage("[--vault-name] <vault-name> [options]").option("-u, --vault-name <vault-name>", $("the vault name")).option("-g, --resource-group <resource-group>", $("changes only if vault belongs to the informed resource group; otherwise returns 'not found'")).option("--object-id <object-id>", $("a GUID that identifies the principal that will receive permissions")).option("--spn <service-principal-name>", $("name of a service principal that will receive permissions")).option("--upn <user-principal-name>", $("name of a user principal that will receive permissions")).option("--perms-to-keys <perms-to-keys>", util.format($("JSON-encoded array of strings representing key operations; each string can be one of [%s]"), KEY_PERMS.join(", "))).option("--perms-to-secrets <perms-to-secrets>", util.format($("JSON-encoded array of strings representing secret operations; each string can be one of [%s]"), SECRET_PERMS.join(", "))).option("--enabled-for-deployment <boolean>", $("specifies whether the Azure Compute resource provider can access secrets")).option("--enabled-for-template-deployment <boolean>", $("specifies whether Azure Resource Manager can access secrets")).option("--enabled-for-disk-encryption <boolean>", $("specifies whether Azure Disk Encryption can access secrets")).option("-s, --subscription <subscription>", $("the subscription identifier")).execute(function __6(vaultName, options, _) { var v, extraneous, subscription, client, identity, resourceGroup, vaultResource, properties, policies, policy, index, request; var __frame = { name: "__6", line: 495 }; return __func(_, this, arguments, __6, 2, __frame, function __$__6() {



















      log.verbose(("arguments: " + JSON.stringify({
        vaultName: vaultName,
        options: options })));


      options.vaultName = (options.vaultName || vaultName);

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


      options.permsToKeys = kvUtils.parseArrayArgument("perms-to-keys", options.permsToKeys, KEY_PERMS, null);
      options.permsToSecrets = kvUtils.parseArrayArgument("perms-to-secrets", options.permsToSecrets, SECRET_PERMS, null);
      options.enabledForDeployment = kvUtils.parseBooleanArgument("enabled-for-deployment", options.enabledForDeployment);
      options.enabledForTemplateDeployment = kvUtils.parseBooleanArgument("enabled-for-template-deployment", options.enabledForTemplateDeployment);
      options.enabledForDiskEncryption = kvUtils.parseBooleanArgument("enabled-for-disk-encryption", options.enabledForDiskEncryption);

      if (((((!options.permsToKeys && !options.permsToSecrets) && __.isUndefined(options.enabledForDeployment)) && __.isUndefined(options.enabledForTemplateDeployment)) && __.isUndefined(options.enabledForDiskEncryption))) {
        log.error($("Please inform at least one of the following:"));
        log.error($("    --perms-to-keys <perms-to-keys>"));
        log.error($("    --perms-to-secrets <perms-to-secrets>"));
        log.error($("    --enabled-for-deployment <boolean>"));
        log.error($("    --enabled-for-template-deployment <boolean>"));
        log.error($("    --enabled-for-disk-encryption <boolean>"));
        return _(new Error($("Inconsistent arguments"))); } ; return (function __$__6(__then) {


        if ((options.permsToKeys || options.permsToSecrets)) {

          v = [];
          if (options.objectId) { v.push("--object-id"); } ;
          if (options.spn) { v.push("--spn"); } ;
          if (options.upn) { v.push("--upn"); } ;

          if ((v.length === 0)) {
            log.error($("You must inform one of:"));
            log.error($("    --object-id <object-id>"));
            log.error($("    --spn <service-principal-name>"));
            log.error($("    --upn <user-principal-name>"));
            return _(new Error($("Could not establish principal to set permissions"))); } ;


          if ((v.length > 1)) {
            return _(new Error(util.format($("Ambiguous arguments: [%s]"), v.join(", ")))); } ; return (function __$__6(__then) {


            if (!options.objectId) {
              return getObjectId(subscription, options.spn, options.upn, __cb(_, __frame, 53, 29, function ___(__0, __3) { options.objectId = __3; __then(); }, true)); } else { __then(); } ; })(__then); } else {





          if (options.objectId) { extraneous = "--object-id"; } ;
          if (options.spn) { extraneous = "--spn"; } ;
          if (options.upn) { extraneous = "--upn"; } ;

          if (extraneous) {
            return _(new Error(util.format($("Inconsistent arguments: %s was informed while none of [--perms-to-keys, --perms-to-secrets] was informed"), extraneous))); } ; __then(); } ; })(function __$__6() {








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





        identity = createVaultIdentity(options.vaultName);


        return withProgress(util.format($("Loading vault %s"), options.vaultName), function __1(log, _) { var __frame = { name: "__1", line: 579 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() { return (function __$__1(_) {

              var __1 = options.resourceGroup; if (__1) { return _(null, __1); } ; return getVaultResourceGroup(client, options.vaultName, __cb(_, __frame, 1, 51, _, true)); })(__cb(_, __frame, -578, 17, function ___(__0, __2) { resourceGroup = __2;
              if (!resourceGroup) {
                return _(null, null); } ;

              return groupUtils.getResource(client, resourceGroup, identity, __cb(_, __frame, 5, 28, _, true)); }, true)); }); }, __cb(_, __frame, 83, 26, function ___(__0, __4) { vaultResource = __4;


          if (!vaultResource) {
            return _(notFoundError(options.resourceGroup, options.vaultName)); } ;


          properties = vaultResource.properties;

          if ((options.permsToKeys || options.permsToSecrets)) {





            policies = properties.accessPolicies;
            policy = __.find(policies, function(item) {
              return (utils.ignoreCaseEquals(item.tenantId, properties.tenantId) && utils.ignoreCaseEquals(item.objectId, options.objectId)); });


            if (!policy) {

              policy = {
                tenantId: properties.tenantId,
                objectId: options.objectId,
                permissions: {
                  keys: [],
                  secrets: [] } };


              policies.push(policy); } ;






            if (options.permsToKeys) {
              policy.permissions.keys = options.permsToKeys; } ;


            if (options.permsToSecrets) {
              policy.permissions.secrets = options.permsToSecrets; } ;



            if ((!policy.permissions.keys.length && !policy.permissions.secrets.length)) {
              index = policies.indexOf(policy);
              policies.splice(index, 1); } ; } ;



          if (!__.isUndefined(options.enabledForDeployment)) {
            properties.enabledForDeployment = options.enabledForDeployment; } ;


          if (!__.isUndefined(options.enabledForTemplateDeployment)) {
            properties.enabledForTemplateDeployment = options.enabledForTemplateDeployment; } ;


          if (!__.isUndefined(options.enabledForDiskEncryption)) {
            properties.enabledForDiskEncryption = options.enabledForDiskEncryption; } ;






          request = {
            location: vaultResource.location,
            properties: properties,
            tags: vaultResource.tags };


          log.verbose(("request: " + JSON.stringify(request)));

          return withProgress(util.format($("Updating vault %s"), options.vaultName), function __2(log, _) { var __frame = { name: "__2", line: 661 }; return __func(_, this, arguments, __2, 1, __frame, function __$__2() {

              return client.resources.createOrUpdate(resourceGroup, identity.resourceProviderNamespace, identity.parentResourcePath, identity.resourceType, identity.resourceName, identity.resourceProviderApiVersion, request, __cb(_, __frame, 1, 34, _, true)); }); }, __cb(_, __frame, 165, 22, function ___(__0, __5) { vaultResource = __5;









            log.info(util.format($("Vault %s was updated"), options.vaultName));
            return showVault(vaultResource, __cb(_, __frame, 178, 6, function __$__6() { _(); }, true)); }, true)); }, true)); }); }); });



  vault.command("delete-policy [vault-name]").description($("Removes an access policy from a vault")).usage("[--vault-name] <vault-name> [options]").option("-u, --vault-name <vault-name>", $("the vault name")).option("-g, --resource-group <resource-group>", $("deletes only if vault belongs to the informed resource group; otherwise returns 'not found'")).option("--object-id <object-id>", $("a GUID that identifies the principal that will lose permissions")).option("--spn <service-principal-name>", $("name of a service principal that will lose permissions")).option("--upn <user-principal-name>", $("name of a user principal that will lose permissions")).option("--enabled-for-deployment", $("if provided, will set the enabledForDeployment property to false in the vault")).option("--enabled-for-template-deployment", $("if provided, will set the enabledForTemplateDeployment property to false in the vault")).option("--enabled-for-disk-encryption", $("if provided, will set the enabledForDiskEncryption property to false in the vault")).option("-s, --subscription <subscription>", $("the subscription identifier")).execute(function __7(vaultName, options, _) { var v, subscription, client, identity, resourceGroup, vaultResource, properties, changed, policies, previousLength, request; var __frame = { name: "__7", line: 689 }; return __func(_, this, arguments, __7, 2, __frame, function __$__7() {

















      log.verbose(("arguments: " + JSON.stringify({
        vaultName: vaultName,
        options: options })));


      options.vaultName = (options.vaultName || vaultName);

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


      v = [];
      if (options.objectId) { v.push("--object-id"); } ;
      if (options.spn) { v.push("--spn"); } ;
      if (options.upn) { v.push("--upn"); } ;

      if (((((v.length === 0) && !options.enabledForDeployment) && !options.enabledForTemplateDeployment) && !options.enabledForDiskEncryption)) {
        log.error($("You must inform one of:"));
        log.error($("    --object-id <object-id>"));
        log.error($("    --spn <service-principal-name>"));
        log.error($("    --upn <user-principal-name>"));
        log.error($("    --enabled-for-deployment"));
        log.error($("    --enabled-for-deployment"));
        log.error($("    --enabled-for-template-deployment"));
        log.error($("    --enabled-for-disk-encryption"));
        return _(new Error($("Missing required argument"))); } ;


      if ((v.length > 1)) {
        return _(new Error(util.format($("Ambiguous arguments: [%s]"), v.join(", ")))); } ; return (function __$__7(__then) {


        if (!options.objectId) {
          return getObjectId(subscription, options.spn, options.upn, __cb(_, __frame, 39, 27, function ___(__0, __3) { options.objectId = __3; __then(); }, true)); } else { __then(); } ; })(function __$__7() {






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





        identity = createVaultIdentity(options.vaultName);


        return withProgress(util.format($("Loading vault %s"), options.vaultName), function __1(log, _) { var __frame = { name: "__1", line: 746 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() { return (function __$__1(_) {

              var __1 = options.resourceGroup; if (__1) { return _(null, __1); } ; return getVaultResourceGroup(client, options.vaultName, __cb(_, __frame, 1, 51, _, true)); })(__cb(_, __frame, -745, 17, function ___(__0, __2) { resourceGroup = __2;
              if (!resourceGroup) {
                return _(null, null); } ;

              return groupUtils.getResource(client, resourceGroup, identity, __cb(_, __frame, 5, 28, _, true)); }, true)); }); }, __cb(_, __frame, 56, 26, function ___(__0, __4) { vaultResource = __4;


          if (!vaultResource) {
            return _(notFoundError(options.resourceGroup, options.vaultName)); } ;


          properties = vaultResource.properties;
          changed = false;

          if (options.objectId) {





            policies = properties.accessPolicies;
            previousLength = policies.length;
            policies = __.filter(properties.accessPolicies, function(item) {
              return (!utils.ignoreCaseEquals(item.tenantId, properties.tenantId) || !utils.ignoreCaseEquals(item.objectId, options.objectId)); });


            if ((policies.length === previousLength)) {
              log.info($("No policy found for the specified principal")); }
             else {
              properties.accessPolicies = policies;
              changed = true; } ; } ;



          if (options.enabledForDeployment) {
            if ((properties.enabledForDeployment === false)) {
              log.info($("Property \"enabledForDeployment\" is already false")); }
             else {
              properties.enabledForDeployment = false;
              changed = true; } ; } ;



          if (options.enabledForTemplateDeployment) {
            if ((properties.enabledForTemplateDeployment === false)) {
              log.info($("Property \"enabledForTemplateDeployment\" is already false")); }
             else {
              properties.enabledForTemplateDeployment = false;
              changed = true; } ; } ;



          if (options.enabledForDiskEncryption) {
            if ((properties.enabledForDiskEncryption === false)) {
              log.info($("Property \"enabledForDiskEncryption\" is already false")); }
             else {
              properties.enabledForDiskEncryption = false;
              changed = true; } ; } ;



          if (!changed) {
            log.info($("Nothing to do.")); return _(null); } ;







          request = {
            location: vaultResource.location,
            properties: properties,
            tags: vaultResource.tags };


          log.verbose(("request: " + JSON.stringify(request)));

          return withProgress(util.format($("Updating vault %s"), options.vaultName), function __2(log, _) { var __frame = { name: "__2", line: 826 }; return __func(_, this, arguments, __2, 1, __frame, function __$__2() {

              return client.resources.createOrUpdate(resourceGroup, identity.resourceProviderNamespace, identity.parentResourcePath, identity.resourceType, identity.resourceName, identity.resourceProviderApiVersion, request, __cb(_, __frame, 1, 34, _, true)); }); }, __cb(_, __frame, 136, 22, function ___(__0, __5) { vaultResource = __5;









            log.info(util.format($("Vault %s was updated"), options.vaultName));
            return showVault(vaultResource, __cb(_, __frame, 149, 6, function __$__7() { _(); }, true)); }, true)); }, true)); }); }); });



  function notFoundError(resourceGroup, vaultName) {
    var msg;
    if (resourceGroup) {
      msg = util.format($("Vault not found on resource group %s: %s"), resourceGroup, vaultName); }
     else {
      msg = util.format($("Vault not found: %s"), vaultName); } ;

    throw new Error(msg); };


  function getVaultResourceGroup(client, vaultName, _) { var parameters, resources, i, resourceInformation, name; var __frame = { name: "getVaultResourceGroup", line: 852 }; return __func(_, this, arguments, getVaultResourceGroup, 2, __frame, function __$getVaultResourceGroup() {
      log.verbose(util.format($("Loading resource group of vault %s"), vaultName));
      parameters = { };
      parameters.filter = (("resourceType eq '" + RESOURCE_TYPE) + "'");
      return client.resources.list(parameters, __cb(_, __frame, 4, 37, function ___(__0, __1) { resources = __1;
        for (i = 0; (i < resources.length); i++) {
          resourceInformation = resourceUtils.getResourceInformation(resources[i].id);
          name = (resourceInformation.resourceName || resources[i].name);
          if ((name.toLowerCase() == vaultName.toLowerCase())) {
            return _(null, resourceInformation.resourceGroup); } ; };


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


  function createVaultIdentity(vaultName) {
    return {
      resourceName: vaultName,
      resourceProviderNamespace: resourceUtils.getProviderName(RESOURCE_TYPE),
      resourceProviderApiVersion: API_VERSION,
      resourceType: resourceUtils.getResourceTypeName(RESOURCE_TYPE),
      parentResourcePath: "" }; };



  function getCurrentUserObjectId(_) { var graphClient, currentUserObject; var __frame = { name: "getCurrentUserObjectId", line: 877 }; return __func(_, this, arguments, getCurrentUserObjectId, 0, __frame, function __$getCurrentUserObjectId() {

      graphClient = getGraphClient();
      return graphClient.objects.getCurrentUser(__cb(_, __frame, 3, 48, function ___(__0, __1) { currentUserObject = __1;
        if ((currentUserObject && currentUserObject.objectId)) {
          return _(null, currentUserObject.objectId); } ;


        return _(new Error($("Unable to find object id of current user."))); }, true)); }); };



  function getObjectId(subscription, servicePrincipalName, userPrincipalName, _) { var account; var __frame = { name: "getObjectId", line: 889 }; return __func(_, this, arguments, getObjectId, 3, __frame, function __$getObjectId() { return (function __$getObjectId(__then) {


        if (servicePrincipalName) {
          return getAccountBySPN(servicePrincipalName, __cb(_, __frame, 4, 16, function ___(__0, __1) { account = __1; __then(); }, true)); } else { return (function __$getObjectId(__then) {
            if (userPrincipalName) {
              return getAccountByUPN(userPrincipalName, __cb(_, __frame, 6, 16, function ___(__0, __2) { account = __2; __then(); }, true)); } else {

              return getAccountFromSubscription(subscription, __cb(_, __frame, 8, 16, function ___(__0, __3) { account = __3; __then(); }, true)); } ; })(__then); } ; })(function __$getObjectId() {


        log.verbose(util.format($("Account objectId: %s"), account.objectId));
        return _(null, account.objectId); }); }); };


  function getAccountBySPN(spn, _) { var graphClient, parameters, accounts; var __frame = { name: "getAccountBySPN", line: 904 }; return __func(_, this, arguments, getAccountBySPN, 1, __frame, function __$getAccountBySPN() {

      log.verbose(util.format($("Getting account for SPN %s"), spn));

      graphClient = getGraphClient();

      parameters = { filter: (("servicePrincipalNames/any(c:c eq '" + spn) + "')") };
      return graphClient.servicePrincipals.list(parameters, __cb(_, __frame, 7, 49, function ___(__0, __1) { accounts = __1;
        if ((!accounts || (accounts.length === 0))) {
          return _(new Error(util.format($("Unable to find service principal with spn %s"), spn))); } ;

        if ((accounts.length > 1)) {
          return _(new Error(util.format($("Ambiguity: multiple service principals found with spn %s. You can avoid this by specifying object id."), spn))); } ;

        return _(null, accounts[0]); }, true)); }); };


  function getAccountByUPN(upn, _) { var graphClient, parameters, accounts; var __frame = { name: "getAccountByUPN", line: 921 }; return __func(_, this, arguments, getAccountByUPN, 1, __frame, function __$getAccountByUPN() {

      log.verbose(util.format($("Getting account for UPN %s"), upn));

      graphClient = getGraphClient();

      parameters = { filter: (("userPrincipalName eq '" + upn) + "'") };
      return graphClient.users.list(parameters, __cb(_, __frame, 7, 37, function ___(__0, __1) { accounts = __1;
        if ((!accounts || (accounts.length === 0))) {
          return _(new Error(util.format($("Unable to find user with upn %s"), upn))); } ;

        if ((accounts.length > 1)) {
          return _(new Error(util.format($("Ambiguity: multiple users principals found with upn %s. You can avoid this by specifying object id."), upn))); } ;

        return _(null, accounts[0]); }, true)); }); };


  function getAccountFromSubscription(subscription, _) { var __frame = { name: "getAccountFromSubscription", line: 938 }; return __func(_, this, arguments, getAccountFromSubscription, 1, __frame, function __$getAccountFromSubscription() {

      if (!subscription) {
        return _(new Error("Subscription was not informed.")); } ;


      if (!subscription.user) {
        return _(new Error($("Current credentials are not from a user or service principal. Azure Key Vault does not work with certificate credentials."))); } ; return (function __$getAccountFromSubscription(__break) {


        switch (subscription.user.type) {
        case "user": return getAccountByUPN(subscription.user.name, __cb(_, __frame, 12, 15, _, true));
        case "servicePrincipal":

          return getAccountBySPN(subscription.user.name, __cb(_, __frame, 15, 15, _, true));
          default:

          return _(new Error(util.format($("Unknown user type: %s"), subscription.user.type)));
        }; })(_); }); };




  function getGraphClient() {
    if (!graphClient) {
      var subscription = profile.current.getSubscription();
      graphClient = adUtils.getADGraphClient(subscription); } ;

    return graphClient; };


  function showVault(resource, _) { var resourceInformation, accessPolicies, i; var __frame = { name: "showVault", line: 969 }; return __func(_, this, arguments, showVault, 1, __frame, function __$showVault() {
      if (!resource.name) {
        resourceInformation = resourceUtils.getResourceInformation(resource.id);
        if (resourceInformation.name) {
          resource.name = resourceInformation.name; } ; } ; return (function __$showVault(__then) {


        if (!log.format().json) {
          accessPolicies = resource.properties.accessPolicies;
          i = 0; var __2 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$showVault() { __more = false; if (__2) { ++i; } else { __2 = true; } ; var __1 = (i < accessPolicies.length); if (__1) {
                return resolvePrincipalName(accessPolicies[i], __cb(_, __frame, 10, 8, function __$showVault() { while (__more) { __loop(); }; __more = true; }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(__then); } else { __then(); } ; })(function __$showVault() {



        cli.interaction.formatOutput(resource, function(resource) {
          utils.logLineFormat(resource, log.data); }); _(); }); }); };



  function resolvePrincipalName(accessPolicy, _) { var graphClient, servicePrincipal, user; var __frame = { name: "resolvePrincipalName", line: 988 }; return __func(_, this, arguments, resolvePrincipalName, 1, __frame, function __$resolvePrincipalName() {

      if ((accessPolicy.spn || accessPolicy.upn)) { return _(null); } ;



      log.verbose(util.format($("resolving principal %s"), accessPolicy.objectId));

      graphClient = getGraphClient(); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$resolvePrincipalName() {


            return graphClient.servicePrincipals.get(accessPolicy.objectId, __cb(_, __frame, 11, 59, function ___(__0, __1) { servicePrincipal = __1;
              if (servicePrincipal) {
                accessPolicy.objectId = (((("" + accessPolicy.objectId) + " (spn=") + servicePrincipal.displayName) + ")"); return _(null); } ; __then(); }, true)); }); })(function ___(e, __result) { __catch(function __$resolvePrincipalName() { if (e) { __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$resolvePrincipalName() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$resolvePrincipalName() {






                return graphClient.users.get(accessPolicy.objectId, __cb(_, __frame, 20, 35, function ___(__0, __2) { user = __2;
                  if (user) {
                    accessPolicy.objectId = (((("" + accessPolicy.objectId) + " (upn=") + user.userPrincipalName) + ")"); return _(null); } ; __then(); }, true)); }); })(function ___(e, __result) { __catch(function __$resolvePrincipalName() { if (e) { __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$resolvePrincipalName() { _(); }); }); }); }); }); };};
