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

var cacheUtils = require("../../util/cacheUtils");
var profile = require("../../util/profile");
var utils = require("../../util/utils");
var WebsitesClient = require("./websites/websitesclient");

var linkedRevisionControl = require("../../util/git/linkedrevisioncontrol");

var $ = utils.getLocaleString;

exports.init = function(cli) {
  var log = cli.output;
  var site = cli.category("site");
  var scm = site.category("deployment").description($("Commands to manage your Web Site deployments"));


  scm.command("list [name]").usage("[options] [name]").description($("List your git deployments")).option("--slot <slot>", $("the name of the slot")).option("-m, --max <count>", $("Limit the maximum number of results")).option("-s, --subscription <id>", $("the subscription id")).execute(function __1(name, options, _) { var parsedSiteName, context, repositoryUri; var __frame = { name: "__1", line: 41 }; return __func(_, this, arguments, __1, 2, __frame, function __$__1() {






      parsedSiteName = WebsitesClient.parseSiteName(name);
      context = {
        subscription: profile.current.getSubscription(options.subscription).id,
        maxItems: options.max,
        site: {
          name: parsedSiteName.name,
          slot: (options.slot ? options.slot : parsedSiteName.slot) } };



      return site.ensureRepositoryUri(context, __cb(_, __frame, 11, 31, function ___(__0, __1) { repositoryUri = __1; return (function __$__1(__then) {
          if (repositoryUri) {
            return listDeployments(context, __cb(_, __frame, 13, 8, __then, true)); } else {

            log.error($("Repository is not setup")); __then(); } ; })(_); }, true)); }); });



  scm.command("show <commitId> [name]").usage("[options] <commitId> [name]").description($("Show your git deployment")).option("--slot <slot>", $("the name of the slot")).option("-d, --details", $("Display log details")).option("-s, --subscription <id>", $("the subscription id")).execute(function __2(commitId, name, options, _) { var parsedSiteName, context, repositoryUri, deployment, data, logs, i, details, j; var __frame = { name: "__2", line: 66 }; return __func(_, this, arguments, __2, 3, __frame, function __$__2() {






      parsedSiteName = WebsitesClient.parseSiteName(name);
      context = {
        subscription: profile.current.getSubscription(options.subscription).id,
        shortId: commitId,
        site: {
          name: parsedSiteName.name,
          slot: (options.slot ? options.slot : parsedSiteName.slot) } };



      return site.ensureRepositoryUri(context, __cb(_, __frame, 11, 31, function ___(__0, __1) { repositoryUri = __1;

        return cacheUtils.readCommitId(context, __cb(_, __frame, 13, 36, function ___(__0, __3) { var __2 = !(context.id = __3); return (function __$__2(__then) { if (__2) {

              return scm.doDeploymentsGet(context, __cb(_, __frame, 15, 12, function __$__2() {

                return cacheUtils.readCommitId(context, __cb(_, __frame, 17, 38, function ___(__0, __5) { var __4 = !(context.id = __5); return (function __$__2(__then) { if (__4) {

                      return _(null, log.error(util.format($("Deployment with %s does not exist"), commitId))); } else { __then(); } ; })(__then); }, true)); }, true)); } else { __then(); } ; })(function __$__2() { return (function __$__2(__then) {



              if (repositoryUri) {
                return scm.doDeploymentGet(context, __cb(_, __frame, 24, 29, function ___(__0, __6) { deployment = __6; return (function __$__2(__then) {

                    if (log.format().json) {
                      data = deployment; return (function __$__2(__then) {
                        if (options.details) {
                          return getLogDetails(context, __cb(_, __frame, 29, 24, function ___(__0, __7) { data.logs = __7; __then(); }, true)); } else { __then(); } ; })(function __$__2() {


                        log.json(data); __then(); }); } else {

                      cli.interaction.logEachData("info", deployment); return (function __$__2(__then) {
                        if (options.details) {
                          return getLogDetails(context, __cb(_, __frame, 36, 23, function ___(__0, __8) { logs = __8;
                            for (i = 0; (i < logs.length); ++i) {
                              displayLog(logs[i]);
                              if (logs[i].details) {
                                details = logs[i].details;
                                for (j = 0; (j < details.length); ++j) {
                                  displayLog(details[j]); }; } ; }; __then(); }, true)); } else {




                          log.help($("To see more details, specify -d or --details option")); __then(); } ; })(__then); } ; })(__then); }, true)); } else {



                log.error($("Repository is not setup")); __then(); } ; })(_); }); }, true)); }, true)); }); });



  scm.command("redeploy <commitId> [name]").usage("[options] <commitId> [name]").description($("Redeploy your git deployment")).option("--slot <slot>", $("the name of the slot")).option("-q, --quiet", $("quiet mode, do not ask for redeploy confirmation")).option("-s, --subscription <id>", $("the subscription id")).execute(function __3(commitId, name, options, _) { var parsedSiteName, context, repositoryUri; var __frame = { name: "__3", line: 127 }; return __func(_, this, arguments, __3, 3, __frame, function __$__3() {






      parsedSiteName = WebsitesClient.parseSiteName(name);
      context = {
        subscription: profile.current.getSubscription(options.subscription).id,
        shortId: commitId,
        site: {
          name: parsedSiteName.name,
          slot: (options.slot ? options.slot : parsedSiteName.slot) } };



      return cacheUtils.readCommitId(context, __cb(_, __frame, 11, 36, function ___(__0, __3) { var __2 = !(context.id = __3); return (function __$__3(__then) { if (__2) {
            return _(null, log.error(util.format($("Deployment with %s does not exist"), commitId))); } else { __then(); } ; })(function __$__3() {


          return site.ensureRepositoryUri(context, __cb(_, __frame, 15, 31, function ___(__0, __4) { repositoryUri = __4; return (function __$__3(__then) {
              if (repositoryUri) { return (function __$__3(_) {
                  var __1 = !options.quiet; if (!__1) { return _(null, __1); } ; return cli.interaction.confirm(util.format($("Reploy deployment with %s id? [y/n] "), context.shortId), __cb(_, __frame, 17, 47, function ___(__0, __3) { var __2 = !__3; return _(null, __2); }, true)); })(__cb(_, __frame, -126, 18, function ___(__0, __5) { return (function __$__3(__then) { if (__5) { return _(null); } else { __then(); } ; })(function __$__3() {


                    return scm.doDeploymentPut(context, __cb(_, __frame, 20, 12, function __$__3() {
                      return listDeployments(context, __cb(_, __frame, 21, 8, __then, true)); }, true)); }); }, true)); } else {

                log.error($("Repository is not setup")); __then(); } ; })(_); }, true)); }); }, true)); }); });



  scm.command("github [name]").usage("[options] [name]").description($("Link a website to a github account for deployment")).option("--slot <slot>", $("the name of the slot")).option("--githubusername <username>", $("the github username")).option("--githubpassword <password>", $("the github password")).option("--githubrepository <repository>", $("the github repository full name (i.e. user/repository)")).option("-s, --subscription <id>", $("the subscription id")).execute(function __4(name, options, _) { var parsedSiteName, context, websiteClient;









































    function initializeRemoteRepo(_) { var __frame = { name: "initializeRemoteRepo", line: 196 }; return __func(_, this, arguments, initializeRemoteRepo, 0, __frame, function __$initializeRemoteRepo() {
        log.silly("InitializeRemoteRepo");
        return site.doRepositoryPost(context, __cb(_, __frame, 2, 13, function __$initializeRemoteRepo() {
          return site.ensureRepositoryUri(context, __cb(_, __frame, 3, 13, function __$initializeRemoteRepo() { _(); }, true)); }, true)); }); }; var __frame = { name: "__4", line: 162 }; return __func(_, this, arguments, __4, 2, __frame, function __$__4() { parsedSiteName = WebsitesClient.parseSiteName(name); context = { subscription: profile.current.getSubscription(options.subscription).id, site: { name: parsedSiteName.name, slot: (options.slot ? options.slot : parsedSiteName.slot) }, github: { username: options.githubusername, password: options.githubpassword, repositoryFullName: options.githubrepository }, flags: { } }; if (!context.github.repositoryFullName) { context.flags = { forceRepositorySelection: true }; } ; return site.ensureRepositoryUri(context, __cb(_, __frame, 23, 11, function __$__4() { return (function __$__4(__then) { if (!context.repositoryUri) { return initializeRemoteRepo(__cb(_, __frame, 26, 8, __then, true)); } else { __then(); } ; })(function __$__4() { websiteClient = new WebsitesClient(cli, context.subscription); context.lvcClient = linkedRevisionControl.createClient(cli, "github", websiteClient); return context.lvcClient.init(context, __cb(_, __frame, 31, 24, function __$__4() { return context.lvcClient.deploy(context, __cb(_, __frame, 32, 24, function __$__4() { _(); }, true)); }, true)); }); }, true)); }); });



  var user = scm.category("user").description($("Commands to manage your Web Site deployment users"));


  user.command("set [username] [pass]").usage("[options] [username] [pass]").description($("Set the deployment credentials")).option("-u, --username <gitUsername>", $("the new git username")).option("-p, --pass <gitPassword>", $("the new git password")).option("-s, --subscription <id>", $("the subscription id")).execute(function __5(username, pass, options, _) { var progress, websiteManagementService; var __frame = { name: "__5", line: 212 }; return __func(_, this, arguments, __5, 3, __frame, function __$__5() {






      return cli.interaction.promptIfNotGiven($("Git username: "), username, __cb(_, __frame, 1, 33, function ___(__0, __1) { username = __1;
        return cli.interaction.promptPasswordIfNotGiven($("Git password: "), pass, __cb(_, __frame, 2, 29, function ___(__0, __2) { pass = __2;

          progress = cli.interaction.progress($("Setting user credentials")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__5() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$__5() {

                      return createWebsiteManagementService(profile.current.getSubscription(options.subscription).id, __cb(_, __frame, 6, 39, function ___(__0, __3) { websiteManagementService = __3;
                        return websiteManagementService.webSpaces.createPublishingUser(username, pass, { publishingUserName: username, publishingPassword: pass }, __cb(_, __frame, 7, 43, __then, true)); }, true)); }); })(function ___(e, __result) { __catch(function __$__5() { if (e) {

                        progress.end(); return (function __$__5(__then) {
                          if ((e.messagetemplate === $("This operation is not supported for subscriptions that have co-admins"))) {
                            return portalGitInitInstruction(__cb(_, __frame, 11, 10, __then, true)); } else {

                            return _(e); } ; })(__then); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, 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)); }, true)); }); });



  function portalGitInitInstruction(_) { var href; var __frame = { name: "portalGitInitInstruction", line: 232 }; return __func(_, this, arguments, portalGitInitInstruction, 0, __frame, function __$portalGitInitInstruction() {
      log.help($("You must create your git publishing credentials using the Microsoft Azure portal for co-admin accounts"));
      log.help($("Please follow these steps in the portal:"));
      log.help($("1. In the menu on the left select \"Web Sites\""));
      log.help($("2. Click on any site"));
      log.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"));

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



  scm.doDeploymentsGet = function scm_doDeploymentsGet__6(context, _) { var maxItems, service, progress, options, deployments; var __frame = { name: "scm_doDeploymentsGet__6", line: 246 }; return __func(_, this, arguments, scm_doDeploymentsGet__6, 1, __frame, function __$scm_doDeploymentsGet__6() {
      maxItems = parseInt(context.maxItems, 10);
      if ((!maxItems || (maxItems <= 0))) {
        maxItems = 20; } ;


      return createWebsiteExtensionsClient(context, __cb(_, __frame, 6, 18, function ___(__0, __1) { service = __1;

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



              options = { };
              return service.deployments.list(options, __cb(_, __frame, 13, 44, function ___(__0, __2) { deployments = __2.deployments;
                deployments = ensureShortCommitId(deployments);
                return cacheUtils.saveCommitIds(context, deployments, __cb(_, __frame, 15, 17, function __$scm_doDeploymentsGet__6() {
                  return _(null, deployments.map(formatDeployment)); }, true)); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$scm_doDeploymentsGet__6() {

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



  scm.doDeploymentGet = function scm_doDeploymentGet__7(context, _) { var service, progress; var __frame = { name: "scm_doDeploymentGet__7", line: 268 }; return __func(_, this, arguments, scm_doDeploymentGet__7, 1, __frame, function __$scm_doDeploymentGet__7() {
      return createWebsiteExtensionsClient(context, __cb(_, __frame, 1, 18, function ___(__0, __1) { service = __1;

        progress = cli.interaction.progress($("Getting deployment info")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$scm_doDeploymentGet__7() {

              return service.deployments.get(context.id, __cb(_, __frame, 5, 50, function ___(__0, __3) { var __2 = formatDeployment(__3.deployment); return _(null, __2); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$scm_doDeploymentGet__7() {

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



  scm.doDeploymentPut = function scm_doDeploymentPut__8(context, _) { var service, progress; var __frame = { name: "scm_doDeploymentPut__8", line: 279 }; return __func(_, this, arguments, scm_doDeploymentPut__8, 1, __frame, function __$scm_doDeploymentPut__8() {
      return createWebsiteExtensionsClient(context, __cb(_, __frame, 1, 18, function ___(__0, __1) { service = __1;

        progress = cli.interaction.progress($("Redeploying deployment")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$scm_doDeploymentPut__8() {

              return service.deployments.redeploy(context.id, __cb(_, __frame, 5, 33, _, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$scm_doDeploymentPut__8() {

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



  scm.doLogGet = function scm_doLogGet__9(context, _) { var service, progress, logs; var __frame = { name: "scm_doLogGet__9", line: 290 }; return __func(_, this, arguments, scm_doLogGet__9, 1, __frame, function __$scm_doLogGet__9() {
      return createWebsiteExtensionsClient(context, __cb(_, __frame, 1, 18, function ___(__0, __1) { service = __1;

        progress = cli.interaction.progress($("Getting deployment log info")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$scm_doLogGet__9() {


              return service.deployments.listLogs(context.id, __cb(_, __frame, 6, 37, function ___(__0, __2) { logs = __2.logs;
                return _(null, logs.map(formatLog)); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$scm_doLogGet__9() {

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



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


  function listDeployments(context, _) { var deployments, authorLength, messageLength; var __frame = { name: "listDeployments", line: 307 }; return __func(_, this, arguments, listDeployments, 1, __frame, function __$listDeployments() {
      return scm.doDeploymentsGet(context, __cb(_, __frame, 1, 26, function ___(__0, __1) { deployments = __1;
        authorLength = 0; messageLength = 0;
        if ((deployments && deployments.length)) {
          log.table(deployments, function(row, deployment) {

            row.cell($("Time"), deployment.startTime);
            row.cell($("Commit id"), deployment.shortId);
            row.cell($("Status"), deployment.status);
            authorLength = Math.max(deployment.author.length, authorLength);
            row.cell($("Author"), deployment.author, null, Math.min(authorLength, 15));
            messageLength = Math.max(deployment.message.length, messageLength);
            row.cell($("Message"), deployment.message, null, Math.min(messageLength, 40)); }); }

         else {
          log.info($("No git deployment found")); } ; _(); }, true)); }); };



  function getLogDetails(context, _) { var results, logs, progress, i; var __frame = { name: "getLogDetails", line: 326 }; return __func(_, this, arguments, getLogDetails, 1, __frame, function __$getLogDetails() {

      return scm.doLogGet(context, __cb(_, __frame, 2, 19, function ___(__0, __2) { logs = __2; return (function __$getLogDetails(__then) {
          if ((logs && logs.length)) {
            progress = cli.interaction.progress($("Getting log details")); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getLogDetails() {

                  return async.map(logs, function __1(currentLog, _) { var service, details; var __frame = { name: "__1", line: 332 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() { return (function __$__1(__then) {
                        if (currentLog.hasDetails) {
                          return createWebsiteExtensionsClient(context, __cb(_, __frame, 2, 26, function ___(__0, __1) { service = __1;
                            return service.deployments.getLog(context.id, currentLog.id, __cb(_, __frame, 3, 46, function ___(__0, __2) { details = __2;
                              return _(null, details.map(formatLog)); }, true)); }, true)); } else { __then(); } ; })(_); }); }, __cb(_, __frame, 6, 24, function ___(__0, __3) { results = __3; _(null, null, true); }, true)); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$getLogDetails() {



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


                for (i = 0; (i < logs.length); ++i) {
                  if (results[i]) {
                    logs[i].details = results[i]; } ; };



                return _(null, logs); }); }); } else {

            log.info($("Deployment has no detail"));
            return _(null, []); } ; })(_); }, true)); }); };



  function displayLog(item) {
    if ((item.type === "Warning")) {

      log.warn(((item.short_time + " ") + item.message)); }
     else if ((item.type === "Error")) {

      log.error(((item.short_time + " ") + item.message)); }
     else {

      log.data(((item.short_time + " ") + item.message)); }  ; };



  function fromJsonDate(str) {
    return new Date(str); };


  function formatDate(dt) {
    var date = dt.getDate(), month = (dt.getMonth() + 1);

    date = ((((date < 10) ? "0" : "")) + date);
    month = ((((month < 10) ? "0" : "")) + month);
    return ((((((dt.getFullYear() + "-") + month) + "-") + date) + " ") + dt.toLocaleTimeString()); };


  function dateTimeText(str) {
    return formatDate(fromJsonDate(str)); };


  function deploymentStatusText(status) {
    switch (status) {
    case 0: return "Pending";
    case 1:
      return "Building";
    case 2:
      return "Deploying";
    case 3:
      return "Failed";
    case 4:
      return "Success";
      default:
      return "Unknown";
    }; };



  function logTypeText(type) {
    switch (type) {
    case 0: return "Message";
    case 1:
      return "Warning";
    case 2:
      return "Error";
      default:
      return "Unknown";
    }; };



  function ensureShortCommitId(deployments) {
    return deployments.map(function(deployment) {
      deployment.shortId = deployment.id.substr(0, 10);
      return deployment; }); };



  function formatDeployment(deployment) {
    var timeProperties = ["end_time","last_success_end_time","received_time","start_time",];
    for (var i = 0; (i < timeProperties.length); ++i) {
      if (deployment[timeProperties[i]]) {
        deployment[timeProperties[i]] = dateTimeText(deployment[timeProperties[i]]); } ; };


    deployment.complete = (!!deployment.complete).toString();
    deployment.status = (deployment.active ? "Active" : deploymentStatusText(deployment.status));
    deployment.message = deployment.message.replace(/\s*(.*)\s*?/g, "$1");
    delete deployment.active;

    delete deployment.status_text;
    delete deployment.url;

    delete deployment.log_url;
    return deployment; };


  function formatLog(log) {

    log.hasDetails = !!log.details_url;
    log.log_time = (log.log_time && dateTimeText(log.log_time));
    log.short_time = (log.log_time && log.log_time.replace(/.* +(.*)/g, "$1"));
    log.type = logTypeText(log.type);
    log.shortId = log.id.substr(0, 10);
    delete log.details_url;
    return log; };


  function createWebsiteExtensionsClient(context, _) { var websiteClient, siteData, authData, siteName, hostNameSuffix, service; var __frame = { name: "createWebsiteExtensionsClient", line: 452 }; return __func(_, this, arguments, createWebsiteExtensionsClient, 1, __frame, function __$createWebsiteExtensionsClient() {
      websiteClient = new WebsitesClient(cli, context.subscription);
      return websiteClient.lookupSiteNameAndWebSpace(context, __cb(_, __frame, 2, 18, function __$createWebsiteExtensionsClient() {
        return websiteClient.getSite(context, __cb(_, __frame, 3, 33, function ___(__0, __1) { siteData = __1;
          authData = websiteClient.getRepositoryAuthData(siteData);
          siteName = WebsitesClient.getSiteHostName(context.site.name, context.site.slot);
          return websiteClient.getHostNameSuffix(context.subscription, __cb(_, __frame, 6, 39, function ___(__0, __2) { hostNameSuffix = __2;
            service = utils.createWebSiteExtensionsClient(siteName, hostNameSuffix, authData.username, authData.password);
            service.baseUri = util.format("https://%s.scm.%s:443", siteName, hostNameSuffix);

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