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
















var util = require("util");

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

var $ = utils.getLocaleString;

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

  var ad = cli.category("ad").description($("Commands to display Active Directory objects"));

  var adSP = ad.category("sp").description($("Commands to display Active Directory service principals"));


  adSP.command("list").description($("Get all Active Directory service principals in current subscription's tenant")).option("| more", $("Provides paging support. Press 'Enter' for more information.")).execute(function __1(options, _) { var subscription, client, progress; var __frame = { name: "__1", line: 38 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {



      subscription = profile.current.getSubscription(options.subscription);
      client = adUtils.getADGraphClient(subscription);
      progress = cli.interaction.progress($("Listing Active Directory service principals")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__1() {

            return adUtils.listGraphObjects(client, "servicePrincipal", cli.interaction, log, __cb(_, __frame, 5, 16, function __$__1() { _(null, null, true); }, 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() { _(); }); }); }); });



  adSP.command("show").description($("Get Active Directory service principals")).option("-n --spn <spn>", $("the name of the service principal to return")).option("-o --objectId <objectId>", $("the object id of the service principal to return")).option("-c --search <search>", $("search display name of the service principal starting with the provided value")).execute(function __2(options, _) { var spn, objectId, search, subscription, client, progress, servicePrincipals, parameters, servicePrincipal; var __frame = { name: "__2", line: 54 }; return __func(_, this, arguments, __2, 1, __frame, function __$__2() {





      spn = options.spn;
      objectId = options.objectId;
      search = options.search;

      adUtils.validateParameters({
        spn: spn,
        objectId: objectId,
        search: search });

      subscription = profile.current.getSubscription(options.subscription);
      client = adUtils.getADGraphClient(subscription);
      progress = cli.interaction.progress($("Getting Active Directory service principals"));
      servicePrincipals = [];
      parameters = null; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__2() { return (function __$__2(__then) {

              if (spn) {
                parameters = { filter: (("servicePrincipalNames/any(c:c eq '" + spn) + "')") };
                return client.servicePrincipals.list(parameters, __cb(_, __frame, 18, 55, function ___(__0, __1) { servicePrincipals = __1; __then(); }, true)); } else { return (function __$__2(__then) {
                  if (objectId) {
                    return client.servicePrincipals.get(objectId, __cb(_, __frame, 20, 58, function ___(__0, __2) { servicePrincipal = __2;
                      if (servicePrincipal) {
                        servicePrincipals.push(servicePrincipal); } ; __then(); }, true)); } else {


                    parameters = { filter: (("startswith(displayName,'" + search) + "')") };
                    return client.servicePrincipals.list(parameters, __cb(_, __frame, 26, 55, function ___(__0, __3) { servicePrincipals = __3; __then(); }, true)); } ; })(__then); } ; })(function __$__2() { _(null, null, true); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$__2() {


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


          if ((servicePrincipals.length > 0)) {
            adUtils.displayServicePrincipals(servicePrincipals, cli.interaction, log); }
           else {
            log.data($("No matching service principal was found")); } ; _(); }); }); }); });



  adSP.command("create").description($("Create Active Directory service principal.")).option("-a --applicationId <applicationId>", $((("The application Id for which service principal needs to be created. " + "If this is provided then everything else will be ignored. \nWhen the applicationId is provided it means that the ") + "application was already created and it needs to be used to create the service principal."))).option("-n --name <name>", $("the display name for the application")).option("-m --home-page <home-page>", $("the URL to the application homepage")).option("-b --available", $("indicates if the application will be available to other tenants")).option("-p --password <password>", $("the value for the password credential associated with the application that will be valid for one year by default")).option("-i --identifier-uris <identifier-uris>", $("the comma-delimitied URIs that identify the application")).option("-r --reply-urls <reply-urls>", $("the comma-delimitied application reply urls")).option("--key-value <key-value>", $("the value for the key credentials associated with the application that will be valid for one year by default")).option("--key-type <key-type>", $("the type of the key credentials associated with the application. Acceptable values are AsymmetricX509Cert, Password and Symmetric")).option("--key-usage <key-usage>", $("the usage of the key credentials associated with the application. Acceptable values are Sign and Verify")).option("--start-date <start-date>", $("the start date after which password or key would be valid. Default value is current time")).option("--end-date <end-date>", $("the end date till which password or key is valid. Default value is one year after current time")).execute(function __3(options, _) { var applicationId, application, subscription, client, spParams, servicePrincipal; var __frame = { name: "__3", line: 109 }; return __func(_, this, arguments, __3, 1, __frame, function __$__3() {

















      applicationId = options.applicationId; return (function __$__3(__then) {
        if (!applicationId) {
          return adUtils.createApplication(cli, options.name, options.homePage, options.identifierUris, options, __cb(_, __frame, 4, 34, function ___(__0, __2) { application = __2;
            applicationId = application.appId; __then(); }, true)); } else { __then(); } ; })(function __$__3() {


        subscription = profile.current.getSubscription(options.subscription);
        client = adUtils.getADGraphClient(subscription);

        spParams = {
          accountEnabled: true,
          appId: applicationId };


        return withProgress(util.format($("Creating service principal for application %s"), applicationId), function __1(log, _) { var __frame = { name: "__1", line: 126 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {

            return client.servicePrincipals.create(spParams, __cb(_, __frame, 1, 40, _, true)); }); }, __cb(_, __frame, 16, 29, function ___(__0, __3) { servicePrincipal = __3;


          cli.interaction.formatOutput(servicePrincipal, function(data) {
            if (data) {
              adUtils.displayAServicePrincipal(data, log); } ; }); _(); }, true)); }); }); });




  adSP.command("set [objectId]").description($("Updates the properties of the created Active Directory ServicePrincipal")).usage("[options] <objectId>").option("-o --objectId <objectId>", $("the object id of the servicePrincipal to update.")).option("-n --name <name>", $("the new display name for the application.")).option("-m --home-page <home-page>", $("the new URL to the application homepage")).option("-p --password <password>", $("new value for the password credential associated with the application that will be valid for one year by default")).option("-i --identifier-uris <identifier-uris>", $("new comma-delimitied URI values that identify the application")).option("-r --reply-urls <reply-urls>", $("new comma-delimitied application reply urls")).option("--key-value <key-value>", $("new value for the key credentials associated with the application that will be valid for one year by default")).option("--key-type <key-type>", $("new type of the key credentials associated with the application. Acceptable values are AsymmetricX509Cert, Password and Symmetric. Default value: AsymmetricX509Cert")).option("--key-usage <key-usage>", $("new usage of the key credentials associated with the application. Acceptable values are Sign and Verify. Default value: Verify")).option("--start-date <start-date>", $("new start date value after which password or key would be valid. Default value is current time")).option("--end-date <end-date>", $("new end date value till which password or key is valid. Default value is one year after current time")).execute(function __4(objectId, options, _) { var applicationId, startDate, endDate, keyType, keyUsage, appParams, subscription, client, application, applications, applicationObjectId, servicePrincipal, currentUserObject, parameters; var __frame = { name: "__4", line: 151 }; return __func(_, this, arguments, __4, 2, __frame, function __$__4() {














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


      startDate = (options.startDate ? new Date(Date.parse(options.startDate)) : new Date(Date.now()));










      return (function ___closure(_) { var date, m; if (options.endDate) { return _(null, new Date(Date.parse(options.endDate))); } else { date = new Date(startDate); m = moment(date); m.add(1, "years"); date = new Date(m.toISOString()); return _(null, date); } ; _(); })(__cb(_, __frame, 6, 20, function ___(__0, __2) { endDate = __2;

        keyType = (options.keyType ? options.keyType : "AsymmetricX509Cert");
        keyUsage = (options.keyUsage ? options.keyUsage : "Verify");

        appParams = { };
        if (options) {
          if (options.available) {
            appParams.availableToOtherTenants = true; } ;

          if (options.name) {
            appParams.displayName = options.name; } ;


          if (options.homePage) {
            appParams.homepage = options.homePage; } ;


          if (options.identifierUris) {
            appParams.identifierUris = options.identifierUris.split(","); } ;


          if (options.replyUrls) {
            appParams.replyUrls = options.replyUrls.split(","); } ;


          if (options.password) {
            appParams.passwordCredentials = [{
              startDate: startDate,
              endDate: endDate,
              keyId: utils.uuidGen(),
              value: options.password },]; } ;



          if (options.keyValue) {
            appParams.keyCredentials = [{
              startDate: startDate,
              endDate: endDate,
              keyId: utils.uuidGen(),
              value: options.keyValue,
              usage: keyUsage,
              type: keyType },]; } ; } ;




        subscription = profile.current.getSubscription(options.subscription);
        client = adUtils.getADGraphClient(subscription);

        application = null;
        applications = []; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__4() {



              return client.servicePrincipals.get(objectId, __cb(_, __frame, 71, 52, function ___(__0, __4) { servicePrincipal = __4;
                if (!servicePrincipal) {
                  return _(new Error($(util.format(("A ServicePrincipal with the provided objectId: '%s' was not found. Hence the ServicePrincipal cannot be updated. " + "If you are not sure, then please execute 'azure ad sp list' and find out the correct objectId."), objectId)))); } ;


                applicationId = servicePrincipal.appId;
                parameters = { filter: (("appId eq '" + applicationId) + "'") };
                return client.applications.list(parameters, __cb(_, __frame, 78, 43, function ___(__0, __5) { applications = __5;
                  if ((!applications || ((applications && (applications.length === 0))))) {
                    return _(new Error($(util.format((("The retrieved applicationId: '%s' for the service principal with objectId: '%s' was not found. Hence the " + "ServicePrincipal cannot be updated. If you are not sure, then please execute 'azure ad app list' and find out whether the underlying ") + "application actually exists."), applicationId, objectId)))); } ;



                  applicationObjectId = applications[0].objectId;
                  return withProgress(util.format($("Updating the underlying application with objectId: '%s', for the ServicePrincipal with objectId: '%s'."), applicationObjectId, objectId), function __1(log, _) { var __frame = { name: "__1", line: 237 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {

                      return client.applications.patch(applicationObjectId, appParams, __cb(_, __frame, 1, 37, _, true)); }); }, __cb(_, __frame, 85, 22, function ___(__0, __6) { application = __6; __then(); }, true)); }, true)); }, true)); }); })(function ___(ex, __result) { __catch(function __$__4() { if (ex) { return (function __$__4(__then) {


                  if ((ex.statusCode && (ex.statusCode === 403))) {

                    return client.objects.getCurrentUser(__cb(_, __frame, 92, 49, function ___(__0, __3) { currentUserObject = __3;
                      if (((currentUserObject && currentUserObject.userType) && (currentUserObject.userType === "Guest"))) {
                        return _(new Error($("Updating the ServicePrincipal is not allowed for a Guest user. Please contact your administrator to be added as a member in your tenant."))); } ; __then(); }, true)); } else { __then(); } ; })(function __$__4() {


                  return _(ex); }); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$__4() {


            cli.interaction.formatOutput(application, function(data) {
              if (data) {
                adUtils.displayAApplication(data, log); } ; }); _(); }); }); }, true)); }); });




  adSP.command("delete [objectId]").description($("Deletes Active Directory service principal.")).usage("[options] <objectId>").option("-o --objectId <objectId>", $("the object id of the service principal to delete")).option("-p --preserve-application", $("Default value: false. If you do not want to delete the underlying application then set this flag.")).option("-q, --quiet", $("quiet mode (do not ask for delete confirmation)")).execute(function __5(objectId, options, _) { var subscription, client, progress, servicePrincipal, parameters, applications, applicationObjectId; var __frame = { name: "__5", line: 264 }; return __func(_, this, arguments, __5, 2, __frame, function __$__5() {






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


        var __1 = !options.quiet; if (!__1) { return _(null, __1); } ; return cli.interaction.confirm(util.format($("Delete service principal %s? [y/n] "), objectId), __cb(_, __frame, 5, 45, function ___(__0, __3) { var __2 = !__3; return _(null, __2); }, true)); })(__cb(_, __frame, -263, 17, function ___(__0, __2) { return (function __$__5(__then) { if (__2) { return _(null); } else { __then(); } ; })(function __$__5() {



          subscription = profile.current.getSubscription(options.subscription);
          client = adUtils.getADGraphClient(subscription);
          progress = cli.interaction.progress(util.format($("Deleting service principal %s"), objectId)); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__5() { return (function __$__5(__then) {

                  if (options.preserveApplication) {
                    log.info("Preserving the underlying application.");
                    return client.servicePrincipals.deleteMethod(objectId, __cb(_, __frame, 15, 35, __then, true)); } else {

                    return client.servicePrincipals.get(objectId, __cb(_, __frame, 17, 58, function ___(__0, __3) { servicePrincipal = __3;
                      parameters = { filter: (("appId eq '" + servicePrincipal.appId) + "'") };
                      return client.applications.list(parameters, __cb(_, __frame, 19, 49, function ___(__0, __4) { applications = __4;
                        applicationObjectId = applications[0].objectId;
                        return client.applications.deleteMethod(applicationObjectId, __cb(_, __frame, 21, 30, __then, true)); }, true)); }, 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(_, function __$__5() { _(); }); }); }); }, true)); }); });};
