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
















var url = require("url");

var async = require("async");
var __ = require("underscore");

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


var child_process = require("child_process");

var $ = utils.getLocaleString;

function WebsitesClient(cli, subscription) {
  this.cli = cli;
  this.subscription = subscription;
  this.hostNameSuffix = null;};


__.extend(WebsitesClient, {
  getSiteName: function(name, slot) {
    if ((slot && !WebsitesClient.isProductionSlot(slot))) {
      return util.format("%s(%s)", name, slot); }
     else {
      return name; } ; },



  parseSiteName: function(name) {
    var regExp = /\(([^)]+)\)/;
    var matches = regExp.exec(name);

    if ((matches && (matches.length > 0))) {
      var slot = matches[(matches.length - 1)];
      name = name.replace(util.format("(%s)", slot), "");

      if (!WebsitesClient.isProductionSlot(slot)) {
        return { name: name, slot: slot }; }
       else {
        return { name: name }; } ; }

     else {
      return { name: name }; } ; },



  getSiteHostName: function(name, slot) {
    if ((slot && !WebsitesClient.isProductionSlot(slot))) {
      return util.format("%s-%s", name, slot); }
     else {
      return name; } ; },



  isProductionSlot: function(slot) {
    return utils.ignoreCaseEquals(slot, this.getProductionSlotName()); },


  isStagingSlot: function(slot) {
    return utils.ignoreCaseEquals(slot, this.getStagingSlotName()); },


  getProductionSlotName: function() {
    return "production"; },


  getStagingSlotName: function() {
    return "staging"; }});



__.extend(WebsitesClient.prototype, {
  enableApplicationDiagnostic: function(name, output, properties, callback) {
    this.setApplicationDiagnosticsSettings(name, output, true, properties, callback); },


  disableApplicationDiagnostic: function(name, output, properties, callback) {
    this.setApplicationDiagnosticsSettings(name, output, false, properties, callback); },


  setApplicationDiagnosticsSettings: function(name, output, setFlag, properties, callback) {
    var self = this;
    var context = {
      subscription: self.subscription,
      site: {
        name: name } };



    self.cli.category("site").lookupSiteNameAndWebSpace(context, function(err) {
      if (err) { return callback(err); } ;

      self.cli.category("site").ensureRepositoryUri(context, function(err, repositoryUri) {
        if (err) { return callback(err); } ;

        if (repositoryUri) {
          self.getDiagnosticsSettings(context, function(err, settings) {
            if (err) { return callback(err); } ;

            if ((!output && setFlag)) {
              throw new Error($("Invalid trace output")); } ;


            if ((!output || (output.toLowerCase() === "file"))) {
              settings.AzureDriveEnabled = setFlag;
              if (setFlag) {
                settings.AzureDriveTraceLevel = properties.level; } ; } ;



            if ((!output || (output.toLowerCase() === "storage"))) {
              settings.AzureTableEnabled = setFlag;

              if (setFlag) {
                settings.AzureTableTraceLevel = properties.level;

                var storageTableName = "CLOUD_STORAGE_ACCOUNT";
                var storageAccountName = properties.storageAccount;


                self.getStorageServiceConnectionString(storageAccountName, function(err, connectionString) {
                  if (err) { return callback(err); } ;


                  self.setConnectionString(name, storageTableName, connectionString, 3, function(err) {
                    if (err) { return callback(err); } ;

                    self.updateDiagnosticsSettings(context, settings, callback); }); }); }


               else {
                self.updateDiagnosticsSettings(context, settings, callback); } ; }

             else {
              self.updateDiagnosticsSettings(context, settings, callback); } ; }); }


         else {
          self.cli.output.error($("Repository is not setup"));
          callback(new Error($("Repository is not setup"))); } ; }); }); },





  getStorageServiceConnectionString: function(name, callback) {
    var self = this;

    var storageService = self.createStorageClient();

    storageService.storageAccounts.get(name, function(err, properties) {
      if (err) { return callback(err); } ;

      storageService.storageAccounts.getKeys(name, function(err, keys) {
        if (err) { return callback(err); } ;

        var connectionString = util.format("AccountName=%s;AccountKey=%s;BlobEndpoint=%s;QueueEndpoint=%s;TableEndpoint=%s", name, keys.primaryKey, properties.storageAccount.properties.endpoints[0], properties.storageAccount.properties.endpoints[1], properties.storageAccount.properties.endpoints[2]);






        callback(null, connectionString); }); }); },




  setConnectionString: function(name, key, value, connectionStringType, callback) {
    var self = this;
    var context = {
      subscription: self.subscription,
      site: {
        name: name } };



    var siteCategory = self.cli.category("site");
    siteCategory.lookupSiteNameAndWebSpace(context, function(err) {
      if (err) { return callback(err); } ;

      siteCategory.doSiteConfigGet(context, function(err, config) {
        if (err) { return callback(err); } ;

        var connectionString;
        if (config.connectionStrings) {
          connectionString = config.connectionStrings.filter(function(c) {
            return utils.ignoreCaseEquals(c.name, key);
          })[0]; }
         else {
          config.connectionStrings = []; } ;


        if (connectionString) {
          connectionString.connectionString = value;
          connectionString.name = key;
          connectionString.type = connectionStringType; }
         else {
          config.connectionStrings.push({
            connectionString: value,
            name: key,
            type: connectionStringType }); } ;



        siteCategory.doSiteConfigPUT(config, context, callback); }); }); },




  getDiagnosticsSettings: function getDiagnosticsSettings__1(context, _) { var self, service, progress, __this = this; var __frame = { name: "getDiagnosticsSettings__1", line: 230 }; return __func(_, this, arguments, getDiagnosticsSettings__1, 1, __frame, function __$getDiagnosticsSettings__1() { self = __this;


      return __this.createWebsiteExtensionsClient(context, __cb(_, __frame, 3, 23, function ___(__0, __1) { service = __1;

        progress = self.cli.interaction.progress($("Getting diagnostic settings")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getDiagnosticsSettings__1() {

              return service.diagnostics.getSettings(__cb(_, __frame, 7, 33, function ___(__0, __3) { var __2 = __3.settings; return _(null, __2); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$getDiagnosticsSettings__1() {

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



  updateDiagnosticsSettings: function updateDiagnosticsSettings__2(context, settings, _) { var self, service, progress, __this = this; var __frame = { name: "updateDiagnosticsSettings__2", line: 243 }; return __func(_, this, arguments, updateDiagnosticsSettings__2, 2, __frame, function __$updateDiagnosticsSettings__2() { self = __this;


      return __this.createWebsiteExtensionsClient(context, __cb(_, __frame, 3, 23, function ___(__0, __1) { service = __1;

        progress = self.cli.interaction.progress($("Updating diagnostic settings")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$updateDiagnosticsSettings__2() {

              return service.diagnostics.updateSettings({ settings: settings }, __cb(_, __frame, 7, 33, _, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$updateDiagnosticsSettings__2() {

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



  createStorageClient: function() {
    return utils.createStorageClient(profile.current.getSubscription(this.subscription)); },


  createWebsiteManagementService: function(subscription, callback) {
    return utils.createWebsiteClient(profile.current.getSubscription(this.subscription), callback); },


  createWebsiteExtensionsClient: function createWebsiteExtensionsClient__3(context, _) { var service, __this = this; var __frame = { name: "createWebsiteExtensionsClient__3", line: 264 }; return __func(_, this, arguments, createWebsiteExtensionsClient__3, 1, __frame, function __$createWebsiteExtensionsClient__3() {


      return __this.getHostNameSuffix(context.subscription, __cb(_, __frame, 3, 11, function ___(__0, __1) { service = utils.createWebSiteExtensionsClient(WebsitesClient.getSiteHostName(context.site.name, context.site.slot), __1, context.repositoryAuth.split(":")[0], context.repositoryAuth.split(":")[1]);


        service.baseUri = context.repositoryUri;

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


  createSite: function createSite__4(subscription, webspace, site, _) { var self, service, progress, errormessageargs, result, siteName, __this = this; var __frame = { name: "createSite__4", line: 275 }; return __func(_, this, arguments, createSite__4, 3, __frame, function __$createSite__4() { self = __this;


      if (site.hostNames) {
        self.cli.output.info(util.format($("Creating a new web site at %s"), site.hostNames)); } ;


      self.cli.output.verbose("Subscription", subscription);
      self.cli.output.verbose("Webspace", webspace);
      self.cli.output.verbose("Site", site.name);

      if (site.slot) {
        self.cli.output.verbose("Slot", site.slot); } ;


      return self.createWebsiteManagementService(subscription, __cb(_, __frame, 15, 23, function ___(__0, __1) { service = __1;
        progress = self.cli.interaction.progress($("Sending site information")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$createSite__4() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$createSite__4() {


                    return service.webSites.create(webspace, site, __cb(_, __frame, 19, 36, function ___(__0, __2) { result = __2.webSite;
                      self.cli.output.info(util.format($("Created website at %s"), result.hostNames));
                      self.cli.output.verbose("Site", result);

                      siteName = WebsitesClient.getSiteName(site.name, site.slot);
                      return cacheUtils.saveSite(subscription, siteName, result, __cb(_, __frame, 24, 17, function __$createSite__4() {


                        return self.getSpaces({ subscription: subscription }, __cb(_, __frame, 27, 11, function __$createSite__4() {
                          return _(null, result); }, true)); }, true)); }, true)); }); })(function ___(err, __result) { __catch(function __$createSite__4() { if (err) {

                      if ((err.statusCode === 500)) {
                        err.message = ((((("The server encountered an internal error. There is a bright chance " + "that the site may be actually created.\nPlease execute: 'azure site list' to verify ") + "that the created site: '") + siteName) + "' appears in the list.\n If it does not appear ") + "in the list then, retry the request.\n"); } ;





                      utils.logError(self.cli.output, $("Failed to create site"), err);
                      if (err.messagetemplate) {
                        errormessageargs = [];
                        if ((err.parameters && err.parameters["a:string"])) {
                          if (__.isArray(err.parameters["a:string"])) {
                            errormessageargs = err.parameters["a:string"]; }
                           else {
                            errormessageargs = [err.parameters["a:string"],]; } ;

                          errormessageargs.unshift($(err.messagetemplate.replace(/\{.*?\}/g, "%s")));
                          return _(new Error(new Error(util.format.apply(err.messagetemplate, errormessageargs)))); }
                         else {
                          return _(new Error(err.messagetemplate)); } ; } else {

                        if ((typeof err.message !== "string")) {
                          return _(new Error($("Invalid service request"))); }
                         else {
                          return _(err); } ; } ; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$createSite__4() { _(null, null, true); }); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$createSite__4() {


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



  createRepository: function(options, callback) {
    var self = this;

    self.cli.output.info($("Initializing remote Azure repository"));
    self.cli.output.verbose("Subscription", options.subscription);
    self.cli.output.verbose("Webspace", options.site.webspace);
    self.cli.output.verbose("Site", options.site.name);

    var progress = self.cli.interaction.progress($("Updating site information"));
    self.createWebsiteManagementService(options.subscription, function(err, service) {
      if (err) {
        return callback(err); } ;

      var siteName = WebsitesClient.getSiteName(options.site.name, options.site.slot);
      service.webSites.createRepository(options.site.webspace, siteName, function(err, result) {
        progress.end();
        if (err) {
          utils.logError(self.cli.output, $("Failed to initialize repository"), err); }
         else {
          self.cli.output.info($("Remote azure repository initialized")); } ;

        return callback(err, result); }); }); },




  getRepository: function getRepository__5(options, _) { var self, siteData, __this = this; var __frame = { name: "getRepository__5", line: 362 }; return __func(_, this, arguments, getRepository__5, 1, __frame, function __$getRepository__5() { self = __this;


      return self.getSite(options, __cb(_, __frame, 3, 24, function ___(__0, __1) { siteData = __1;
        return _(null, self.getRepositoryUri(siteData)); }, true)); }); },


  deleteRepository: function(options, callback) {
    var self = this;

    self.cli.output.verbose("Subscription", options.subscription);
    self.cli.output.verbose("Webspace", options.site.webspace);
    self.cli.output.verbose("Site", options.site.name);

    var progress = self.cli.interaction.progress($("Updating site information"));
    self.createWebsiteManagementService(options.subscription, function(err, service) {
      if (err) {
        return callback(err); } ;

      var siteName = WebsitesClient.getSiteName(options.site.name, options.site.slot);
      service.webSites.deleteRepository(options.site.webspace, siteName, function(err, result) {
        progress.end();
        if (err) {
          utils.logError(self.cli.output, $("Failed to delete repository"), err); }
         else {
          self.cli.output.info($("Repository deleted")); } ;


        return callback(err, result); }); }); },






  syncRepository: function(options, callback) {
    var self = this;

    self.cli.output.verbose("Subscription", options.subscription);
    self.cli.output.verbose("Webspace", options.site.webspace);
    self.cli.output.verbose("Site", options.site.name);

    var progress = self.cli.interaction.progress($("Sync site repository"));

    var siteName = WebsitesClient.getSiteName(options.site.name, options.site.slot);


    var oldService = utils.createWebsiteManagementService(profile.current.getSubscription(self.subscription), self.cli.output);
    oldService.syncSiteRepository(options.site.webspace, siteName, function(err, result) {
      progress.end();
      if (err) {
        utils.logError(self.cli.output, $("Failed to sync repository"), err); }
       else {
        self.cli.output.info($("Repository sync completed")); } ;

      return callback(err, result); }); },



  getSpaces: function getSpaces__6(options, _) { var self, progress, message, href, service, spaces, __this = this; var __frame = { name: "getSpaces__6", line: 421 }; return __func(_, this, arguments, getSpaces__6, 1, __frame, function __$getSpaces__6() { self = __this;

      self.cli.output.verbose("Subscription", options.subscription);

      progress = self.cli.interaction.progress($("Getting locations")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getSpaces__6() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getSpaces__6() {

                  return self.createWebsiteManagementService(options.subscription, __cb(_, __frame, 6, 25, function ___(__0, __2) { service = __2;
                    return service.webSpaces.list(__cb(_, __frame, 7, 37, function ___(__0, __3) { spaces = __3.webSpaces;
                      return cacheUtils.saveSpaces(options, spaces, __cb(_, __frame, 8, 17, function __$getSpaces__6() {
                        return _(null, spaces); }, true)); }, true)); }, true)); }); })(function ___(err, __result) { __catch(function __$getSpaces__6() { if (err) {

                    message = err.Message; return (function __$getSpaces__6(__then) {
                      if (((typeof message === "string") && (message.indexOf("Access is denied.") >= 0))) {
                        self.cli.output.error($("Please use the Microsoft Azure portal to create your first web website"));
                        self.cli.output.error($("You can do so by following these steps:"));
                        self.cli.output.error($("1. At the bottom of the page, click on New > Web Site > Quick Create"));
                        self.cli.output.error($("2. Type a valid site name in the URL field"));
                        self.cli.output.error($("3. Click on \"Create Web Site\""));
                        self.cli.output.error($("4. Once the site has been created, click on the site name"));
                        self.cli.output.error($("5. Click on \"Set up Git publishing\" or \"Reset deployment credentials\" and setup a publishing username and password. Use those credentials for all new websites you create"));

                        return confirm($("Launch browser to portal now? [y/n] "), __cb(_, __frame, 21, 12, function ___(__0, __1) { return (function __$getSpaces__6(__then) { if (__1) {
                              self.cli.output.help($("Launching portal"));
                              href = profile.current.getSubscription().getPortalUrl();
                              return self.cli.interaction.launchBrowser(href, __cb(_, __frame, 24, 31, __then, true)); } else { __then(); } ; })(__then); }, true)); } else { __then(); } ; })(function __$getSpaces__6() {



                      return _(err); }); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$getSpaces__6() { _(null, null, true); }); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$getSpaces__6() {

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



  getSites: function getSites__7(context, _) { var self, progress, service, result, sites, __this = this; var __frame = { name: "getSites__7", line: 455 }; return __func(_, this, arguments, getSites__7, 1, __frame, function __$getSites__7() { self = __this;

      self.cli.output.verbose("Subscription", context.subscription);


      return self.createWebsiteManagementService(context.subscription, __cb(_, __frame, 5, 23, function ___(__0, __2) { service = __2;

        return self.ensureSpaces(context, __cb(_, __frame, 7, 9, function __$getSites__7() {

          progress = self.cli.interaction.progress($("Getting sites")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getSites__7() {

                return async.map(context.spaces, function __1(webspace, _) { var __frame = { name: "__1", line: 467 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {

                    return service.webSpaces.listWebSites(webspace.name, {
                      propertiesToInclude: ["repositoryuri","publishingpassword","publishingusername",] }, __cb(_, __frame, 1, 35, function ___(__0, __2) {




                      var __1 = __2.webSites; return _(null, __1); }, true)); }); }, __cb(_, __frame, 11, 25, function ___(__0, __3) { result = __3;



                  sites = [];

                  result.forEach(function(item) {
                    sites = sites.concat(item); });


                  self.cli.output.json("verbose", sites);
                  return cacheUtils.saveSites(context.subscription, sites, __cb(_, __frame, 30, 17, function __$getSites__7() {
                    return _(null, sites); }, true)); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$getSites__7() {


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



  getSite: function getSite__8(options, _) { var self, service, result, progress, siteName, __this = this; var __frame = { name: "getSite__8", line: 493 }; return __func(_, this, arguments, getSite__8, 1, __frame, function __$getSite__8() {
      validate.validateArgs("getSite", function(v) {
        v.object(options, "options");
        v.object(options.site, "options.site");
        v.string(options.site.name, "options.site.name");
        v.string(options.site.webspace, "options.site.webspace"); }); self = __this;




      return self.createWebsiteManagementService(options.subscription, __cb(_, __frame, 10, 23, function ___(__0, __1) { service = __1;


        progress = self.cli.interaction.progress($("Getting site information")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getSite__8() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getSite__8() {


                    siteName = WebsitesClient.getSiteName(options.site.name, options.site.slot);
                    return service.webSites.get(options.site.webspace, siteName, {
                      propertiesToInclude: ["repositoryuri","publishingpassword","publishingusername",] }, __cb(_, __frame, 17, 32, function ___(__0, __2) { result = __2.webSite;


                      self.cli.output.verbose("Site", result);
                      return cacheUtils.saveSite(options.subscription, siteName, result, __cb(_, __frame, 22, 17, __then, true)); }, true)); }); })(function ___(err, __result) { __catch(function __$getSite__8() { if (err) {

                      utils.logError(self.cli.output, $("Failed to get site info"), err);
                      if ((err.Code === "NotFound")) {
                        return _(null, cacheUtils.deleteSite(options.subscription, siteName, function() {
                          throw err; })); }

                       else {
                        return _(err); } ; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$getSite__8() { _(null, null, true); }); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$getSite__8() {


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

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


  getSiteInstances: function getSiteInstances__9(options, _) { var self, service, result, progress, siteName, __this = this; var __frame = { name: "getSiteInstances__9", line: 531 }; return __func(_, this, arguments, getSiteInstances__9, 1, __frame, function __$getSiteInstances__9() {
      validate.validateArgs("getSiteInstances", function(v) {
        v.object(options, "options");
        v.object(options.site, "options.site");
        v.string(options.site.name, "options.site.name");
        v.string(options.site.webspace, "options.site.webspace"); }); self = __this;




      return self.createWebsiteManagementService(options.subscription, __cb(_, __frame, 10, 23, function ___(__0, __1) { service = __1;


        progress = self.cli.interaction.progress($("Getting site instances information")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getSiteInstances__9() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getSiteInstances__9() {


                    siteName = WebsitesClient.getSiteName(options.site.name, options.site.slot);
                    return service.webSites.getInstanceIds(options.site.webspace, siteName, __cb(_, __frame, 17, 32, function ___(__0, __2) { result = __2;

                      self.cli.output.verbose("Instance Ids", result); __then(); }, true)); }); })(function ___(err, __result) { __catch(function __$getSiteInstances__9() { if (err) {

                      utils.logError(self.cli.output, $("Failed to get site instances info"), err);
                      return _(err); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$getSiteInstances__9() { _(null, null, true); }); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$getSiteInstances__9() {

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


            return _(null, result.instanceIds); }); }); }, true)); }); },


  updateSite: function updateSite__10(site, options, _) { var self, progress, service, __this = this; var __frame = { name: "updateSite__10", line: 561 }; return __func(_, this, arguments, updateSite__10, 2, __frame, function __$updateSite__10() { self = __this;


      progress = self.cli.interaction.progress($("Updating site information")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$updateSite__10() {


            return self.createWebsiteManagementService(options.subscription, __cb(_, __frame, 6, 25, function ___(__0, __1) { service = __1;
              return service.webSites.update(options.site.webspace, WebsitesClient.getSiteName(options.site.name, options.site.slot), site, __cb(_, __frame, 7, 30, _, true)); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$updateSite__10() {

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



  getSiteConfiguration: function(options, callback) {
    var self = this;
    var progress = self.cli.interaction.progress($("Getting site config information"));

    var siteName = WebsitesClient.getSiteName(options.site.name, options.site.slot);
    self.createWebsiteManagementService(options.subscription, function(err, service) {
      if (err) {
        return callback(err); } ;

      service.webSites.getConfiguration(options.site.webspace, siteName, function(err, result) {
        progress.end();
        if (err) {
          utils.logError(self.cli.output, $("Failed to get site config info"), err); }
         else {
          self.cli.output.verbose("SiteConfig", result); } ;

        return callback(err, result); }); }); },




  updateSiteConfiguration: function updateSiteConfiguration__11(config, options, _) { var self, progress, service, siteName, __this = this; var __frame = { name: "updateSiteConfiguration__11", line: 595 }; return __func(_, this, arguments, updateSiteConfiguration__11, 2, __frame, function __$updateSiteConfiguration__11() { self = __this;


      progress = self.cli.interaction.progress($("Updating site config information")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$updateSiteConfiguration__11() {


            return self.createWebsiteManagementService(options.subscription, __cb(_, __frame, 6, 25, function ___(__0, __1) { service = __1;

              siteName = WebsitesClient.getSiteName(options.site.name, options.site.slot);
              return service.webSites.updateConfiguration(options.site.webspace, siteName, config, __cb(_, __frame, 9, 30, _, true)); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$updateSiteConfiguration__11() {

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



  getAvailableLocations: function getAvailableLocations__12(options, _) { var self, progress, service, locations, result, webspaces, __this = this; var __frame = { name: "getAvailableLocations__12", line: 610 }; return __func(_, this, arguments, getAvailableLocations__12, 1, __frame, function __$getAvailableLocations__12() { self = __this;


      self.cli.output.verbose("Subscription", options.subscription);

      progress = self.cli.interaction.progress($("Getting locations")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getAvailableLocations__12() {

            return self.createWebsiteManagementService(options.subscription, __cb(_, __frame, 7, 25, function ___(__0, __1) { service = __1;


              return service.webSpaces.listGeoRegions(__cb(_, __frame, 10, 40, function ___(__0, __2) { locations = __2.geoRegions;
                result = locations.map(function(location) {
                  return {
                    name: location.name,
                    webSpace: utils.webspaceFromName(location.name) }; });




                return service.webSpaces.list(__cb(_, __frame, 19, 40, function ___(__0, __3) { webspaces = __3.webSpaces;
                  webspaces.forEach(function(webspace) {
                    if (!result.some(function(loc) {
                      return (loc.webSpace === webspace.name);
                    })) {
                      result.push({
                        name: webspace.geoRegion,
                        webSpace: webspace.name }); } ; });







                  result = __.uniq(result, function(item) { return item.name; });
                  return _(null, result); }, true)); }, true)); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$getAvailableLocations__12() {

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



  getPublishingUsers: function getPublishingUsers__13(options, _) { var self, progress, service, publishingUsers, __this = this; var __frame = { name: "getPublishingUsers__13", line: 651 }; return __func(_, this, arguments, getPublishingUsers__13, 1, __frame, function __$getPublishingUsers__13() { self = __this;


      progress = self.cli.interaction.progress($("Getting user information")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getPublishingUsers__13() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getPublishingUsers__13() {


                  return self.createWebsiteManagementService(options.subscription, __cb(_, __frame, 6, 27, function ___(__0, __1) { service = __1;
                    return service.webSpaces.listPublishingUsers(__cb(_, __frame, 7, 48, function ___(__0, __2) { publishingUsers = __2.users;

                      self.cli.output.verbose($("PublishingUsers"), publishingUsers);
                      return _(null, publishingUsers); }, true)); }, true)); }); })(function ___(e, __result) { __catch(function __$getPublishingUsers__13() { if (e) {


                    return _(null, ["","",]); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$getPublishingUsers__13() { _(null, null, true); }); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$getPublishingUsers__13() {



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



  getHostNameSuffix: function getHostNameSuffix__14(subscription, _) { var self, subscriptionId, websiteManagementService, hostNameSuffix, __this = this; var __frame = { name: "getHostNameSuffix__14", line: 672 }; return __func(_, this, arguments, getHostNameSuffix__14, 1, __frame, function __$getHostNameSuffix__14() { self = __this; return (function __$getHostNameSuffix__14(__then) {

        if (!self.hostNameSuffix) {
          subscription = profile.current.getSubscription(subscription);
          subscriptionId = subscription.id; return (function __$getHostNameSuffix__14(__then) {
            if (subscriptionId) {
              return self.createWebsiteManagementService(subscriptionId, __cb(_, __frame, 6, 44, function ___(__0, __1) { websiteManagementService = __1;
                return websiteManagementService.webSpaces.getDnsSuffix(__cb(_, __frame, 7, 64, function ___(__0, __2) { hostNameSuffix = __2;

                  __this.hostNameSuffix = (hostNameSuffix.dnsSuffix || subscription.hostNameSuffix); __then(); }, true)); }, true)); } else {

              __this.hostNameSuffix = subscription.hostNameSuffix; __then(); } ; })(__then); } else { __then(); } ; })(function __$getHostNameSuffix__14() {


        return _(null, __this.hostNameSuffix); }); }); },


  portalGitInitInstruction: function portalGitInitInstruction__15(context, _) { var self, href, __this = this; var __frame = { name: "portalGitInitInstruction__15", line: 689 }; return __func(_, this, arguments, portalGitInitInstruction__15, 1, __frame, function __$portalGitInitInstruction__15() { self = __this;


      self.cli.output.help($("You must create your git publishing credentials using the Microsoft Azure portal"));
      self.cli.output.help($("Please follow these steps in the portal:"));
      self.cli.output.help($("1. In the menu on the left select \"Web Sites\""));
      self.cli.output.help(util.format($("2. Click on the site named \"%s\" or any other site"), ((((context.site && context.site.name)) || "{site name}"))));
      self.cli.output.help($("3. Click on \"Set up Git publishing\" or \"Reset deployment credentials\" and setup a publishing username and password. Use those credentials for all new websites you create"));
      if (context.git) {
        self.cli.output.help($("4. Back in the console window, rerun this command by typing \"azure site create {site name} --git\"")); } ;


      return self.cli.interaction.confirm($("Launch browser to portal now? [y/n] "), __cb(_, __frame, 12, 29, function ___(__0, __1) { return (function __$portalGitInitInstruction__15(__then) { if (__1) {
            self.cli.output.help($("Launching portal"));
            href = profile.current.getSubscription().getPortalUrl();
            return self.cli.interaction.launchBrowser(href, __cb(_, __frame, 15, 27, __then, true)); } else { __then(); } ; })(_); }, true)); }); },



  getPublishingUser: function getPublishingUser__16(context, _) { var self, administratorSlots, administrators, username, password, websiteManagementService, __this = this;


    function fallbackToPortal(_) { var __frame = { name: "fallbackToPortal", line: 711 }; return __func(_, this, arguments, fallbackToPortal, 0, __frame, function __$fallbackToPortal() {

        return self.portalGitInitInstruction(context, __cb(_, __frame, 2, 11, function __$fallbackToPortal() {
          return _(new Error($("Git credentials needs to be setup on the portal"))); }, true)); }); }; var __frame = { name: "getPublishingUser__16", line: 708 }; return __func(_, this, arguments, getPublishingUser__16, 1, __frame, function __$getPublishingUser__16() { self = __this;


      administratorSlots = context.publishingUsers.map(function(user) {
        return user.name; });


      administrators = administratorSlots.filter(function(item) {
        return ((typeof item === "string") && (item.length <= 64)); });


      if (((administratorSlots.length === 1) && (administrators.length === 1))) {

        return _(null, administrators[0]); } ;


      self.cli.output.help($("Please provide the username for Git deployment")); return (function __$getPublishingUser__16(__then) {

        if ((administratorSlots.length === 1)) {

          self.cli.output.help($("If you are a new git user under this subscription, please also provide a password")); __then(); } else { return (function __$getPublishingUser__16(__then) {
            if ((administrators.length === 0)) {
              return fallbackToPortal(__cb(_, __frame, 28, 6, __then, true)); } else { __then(); } ; })(__then); } ; })(function __$getPublishingUser__16() {


        return self.cli.interaction.prompt($("Publishing username: "), __cb(_, __frame, 31, 40, function ___(__0, __1) { username = __1; return (function __$getPublishingUser__16(__then) {

            if ((administrators.length === 0)) { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getPublishingUser__16() {

                    return self.cli.interaction.promptPassword($("Publishing password: "), __cb(_, __frame, 35, 44, function ___(__0, __2) { password = __2;
                      return self.createWebsiteManagementService(context.subscription, __cb(_, __frame, 36, 44, function ___(__0, __3) { websiteManagementService = __3;
                        return websiteManagementService.webSpaces.createPublishingUser(username, password, { publishingUserName: username, publishingPassword: password }, __cb(_, __frame, 37, 43, __then, true)); }, true)); }, true)); }); })(function ___(e, __result) { __catch(function __$getPublishingUser__16() { if (e) {

                      return fallbackToPortal(__cb(_, __frame, 39, 8, __then, true)); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, __then); }); } else { __then(); } ; })(function __$getPublishingUser__16() {



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


  getRepositoryUri: function(siteData) {
    if ((siteData.siteProperties && siteData.siteProperties.properties)) {
      for (var property in siteData.siteProperties.properties) {
        if (utils.ignoreCaseEquals(property, "RepositoryUri")) {
          if ((typeof siteData.siteProperties.properties[property] === "string")) {
            if (!utils.stringEndsWith(siteData.siteProperties.properties[property], "/")) {

              siteData.siteProperties.properties[property] += "/"; } ;


            return siteData.siteProperties.properties[property]; }
           else {
            return null; } ; } ; }; } ;





    return null; },


  getRepositoryAuthData: function(siteData) {
    var userName, password;
    for (var property in siteData.siteProperties.properties) {
      if (utils.ignoreCaseEquals(property, "PublishingUsername")) {
        userName = siteData.siteProperties.properties[property]; }
       else if (utils.ignoreCaseEquals(property, "PublishingPassword")) {
        password = siteData.siteProperties.properties[property]; }  ; };


    return {
      username: userName,
      password: password }; },



  getRepositoryAuth: function(siteData) {
    var data = this.getRepositoryAuthData(siteData);
    return (data.username && (((data.username + ":") + data.password))); },


  getGitUri: function(repositoryUri, siteName, auth) {
    var repoUrl = url.parse(repositoryUri);

    if (auth) {
      repoUrl.auth = auth; } ;


    var sitePath = (siteName + ".git");

    if (!utils.stringEndsWith(repoUrl.path, "/")) {

      repoUrl.path += "/"; } ;

    repoUrl.path += sitePath;

    if (!utils.stringEndsWith(repoUrl.pathname, "/")) {

      repoUrl.pathname += "/"; } ;

    repoUrl.pathname += sitePath;

    return url.format(repoUrl); },


  ensureRepositoryUri: function ensureRepositoryUri__17(context, _) { var self, siteData, repositoryUri, __this = this; var __frame = { name: "ensureRepositoryUri__17", line: 819 }; return __func(_, this, arguments, ensureRepositoryUri__17, 1, __frame, function __$ensureRepositoryUri__17() { self = __this;


      return self.lookupSiteNameAndWebSpace(context, __cb(_, __frame, 3, 24, function ___(__0, __1) { siteData = __1;
        repositoryUri = (siteData && self.getRepositoryUri(siteData)); return (function __$ensureRepositoryUri__17(__then) {
          if (!repositoryUri) {
            return self.getSite(context, __cb(_, __frame, 6, 22, function ___(__0, __2) { siteData = __2;
              repositoryUri = self.getRepositoryUri(siteData); __then(); }, true)); } else { __then(); } ; })(function __$ensureRepositoryUri__17() {


          if (repositoryUri) {
            context.repositoryAuth = self.getRepositoryAuth(siteData);
            context.repositoryUri = repositoryUri; } ;


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


  lookupSiteName: function lookupSiteName__18(context, _) { var self, cfg, __this = this; var __frame = { name: "lookupSiteName__18", line: 837 }; return __func(_, this, arguments, lookupSiteName__18, 1, __frame, function __$lookupSiteName__18() { self = __this;


      if ((context.site.name !== undefined)) { return _(null); } ;




      return self.readConfig(__cb(_, __frame, 8, 19, function ___(__0, __1) { cfg = __1;
        if ((cfg && cfg.name)) {

          context.site.name = cfg.name;
          if (((cfg.slot !== undefined) && (cfg.slot !== "undefined"))) {
            context.site.slot = cfg.slot; } ;


          context.site.webspace = cfg.webspace; return _(null); } ;



        return self.cli.interaction.prompt($("Web site name: "), __cb(_, __frame, 20, 45, function ___(__0, __2) { context.site.name = __2;
          return self.cli.interaction.prompt($("Web site slot [enter for none]: "), __cb(_, __frame, 21, 45, function ___(__0, __3) { context.site.slot = __3;

            if (!context.site.name) {
              return _(new Error($("Invalid site name"))); } ; _(); }, true)); }, true)); }, true)); }); },



  lookupSiteWebSpace: function lookupSiteWebSpace__19(context, _) { var self, siteName, sites, index, __this = this; var __frame = { name: "lookupSiteWebSpace__19", line: 865 }; return __func(_, this, arguments, lookupSiteWebSpace__19, 1, __frame, function __$lookupSiteWebSpace__19() {
      validate.validateArgs("lookupSiteWebSpace", function(v) {
        v.object(context, "context");
        v.object(context.site, "context.site");
        v.string(context.site.name, "context.site.name"); }); self = __this;




      siteName = WebsitesClient.getSiteName(context.site.name, context.site.slot);

      self.cli.output.verbose(util.format($("Attempting to locate site "), siteName));
      return self.getSites(context, __cb(_, __frame, 12, 21, function ___(__0, __1) { sites = __1;
        for (index in sites) {
          if (utils.ignoreCaseEquals(sites[index].name, siteName)) {
            self.cli.output.verbose(util.format($("Site located at %s"), sites[index].webSpace));
            context.site.webspace = sites[index].webSpace; } ; };



        if ((context.site.webspace === undefined)) {
          return _(new Error(util.format($("Unable to locate site named %s"), siteName))); } ; _(); }, true)); }); },



  lookupSiteNameAndWebSpace: function lookupSiteNameAndWebSpace__20(context, _) { var self, siteName, cache, __this = this; var __frame = { name: "lookupSiteNameAndWebSpace__20", line: 890 }; return __func(_, this, arguments, lookupSiteNameAndWebSpace__20, 1, __frame, function __$lookupSiteNameAndWebSpace__20() { self = __this;


      return self.lookupSiteName(context, __cb(_, __frame, 3, 9, function __$lookupSiteNameAndWebSpace__20() {

        siteName = WebsitesClient.getSiteName(context.site.name, context.site.slot);
        return cacheUtils.readSite(context.subscription, siteName, __cb(_, __frame, 6, 27, function ___(__0, __1) { cache = __1;
          if ((cache || context.site.webspace)) {
            context.site.webspace = (((cache && cache.webSpace)) || context.site.webspace);
            return _(null, cache); } ;


          return self.lookupSiteWebSpace(context, __cb(_, __frame, 12, 9, function __$lookupSiteNameAndWebSpace__20() {

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


  ensureSpaces: function ensureSpaces__21(context, _) { var self, __this = this; var __frame = { name: "ensureSpaces__21", line: 907 }; return __func(_, this, arguments, ensureSpaces__21, 1, __frame, function __$ensureSpaces__21() { self = __this; return (function __$ensureSpaces__21(__then) {

        if (!context.spaces) { return (function __$ensureSpaces__21(__then) {
            if (!context.skipCache) {
              return cacheUtils.readSpaces(context, __cb(_, __frame, 4, 36, function ___(__0, __1) { context.spaces = __1; __then(); }, true)); } else { __then(); } ; })(function __$ensureSpaces__21() { return (function __$ensureSpaces__21(__then) {


              if ((!context.spaces || !context.spaces.length)) {
                return self.getSpaces(context, __cb(_, __frame, 8, 30, function ___(__0, __2) { context.spaces = __2; __then(); }, true)); } else { __then(); } ; })(__then); }); } else { __then(); } ; })(_); }); },







  readConfig: function readConfig__22(_) { var self, __this = this; var __frame = { name: "readConfig__22", line: 923 }; return __func(_, this, arguments, readConfig__22, 0, __frame, function __$readConfig__22() { self = __this;



      return self.readConfigValue("azure.site.name", __cb(_, __frame, 4, 17, function ___(__0, __2) {
        return self.readConfigValue("azure.site.slot", __cb(_, __frame, 5, 17, function ___(__0, __3) {
          return self.readConfigValue("azure.site.webspace", __cb(_, __frame, 6, 21, function ___(__0, __4) { var __1 = { name: __2, slot: __3, webspace: __4 }; return _(null, __1); }, true)); }, true)); }, true)); }); },



  writeConfig: function writeConfig__23(cfg, _) { var self, __this = this; var __frame = { name: "writeConfig__23", line: 933 }; return __func(_, this, arguments, writeConfig__23, 1, __frame, function __$writeConfig__23() { self = __this;


      return self.writeConfigValue("azure.site.name", cfg.name, __cb(_, __frame, 3, 9, function __$writeConfig__23() { return (function __$writeConfig__23(__then) {
          if (cfg.slot) {
            return self.writeConfigValue("azure.site.slot", cfg.slot, __cb(_, __frame, 5, 11, __then, true)); } else { __then(); } ; })(function __$writeConfig__23() {


          return self.writeConfigValue("azure.site.webspace", cfg.webspace, __cb(_, __frame, 8, 9, function __$writeConfig__23() { _(); }, true)); }); }, true)); }); },


  readConfigValue: function readConfigValue__24(name, _) { var self, result, __this = this; var __frame = { name: "readConfigValue__24", line: 944 }; return __func(_, this, arguments, readConfigValue__24, 1, __frame, function __$readConfigValue__24() { self = __this; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$readConfigValue__24() {



            return exec(("git config --get " + name), __cb(_, __frame, 4, 19, function ___(__0, __1) { result = __1;
              return _(null, ((result.stdout + result.stderr)).trim()); }, true)); }); })(function ___(err, __result) { __catch(function __$readConfigValue__24() { if (err) {


              self.cli.output.silly($("Unable to read config"), err);
              return _(null, ""); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$readConfigValue__24() { _(); }); }); }); },



  writeConfigValue: function writeConfigValue__25(name, value, _) { var __frame = { name: "writeConfigValue__25", line: 957 }; return __func(_, this, arguments, writeConfigValue__25, 2, __frame, function __$writeConfigValue__25() {
      return exec(((("git config " + name) + " ") + value), __cb(_, __frame, 1, 4, function __$writeConfigValue__25() { _(); }, true)); }); }});






function exec(cmd, cb) {

  child_process.exec(cmd, function(err, stdout, stderr) {
    cb(err, {
      stdout: stdout,
      stderr: stderr }); });};




module.exports = WebsitesClient;
