<mt:if name="installing">
<mt:setvarblock name="page_title"><__trans phrase="Initializing database..."></mt:setvarblock>
<mt:else>
<mt:setvarblock name="page_title"><__trans phrase="Upgrading database..."></mt:setvarblock>
</mt:if>

<mt:setvar name="complete" value="1">

<mt:setvarblock name="page_content">
<div class="upgrade">
<mt:unless name="up_to_date">
  <div class="card card-block bg-faded">
    <pre id="upgrade-container" class="pre-scrollable upgrade-process">
      <code>
        <ul id="upgrade-progress">
        </ul>
      </code>
    </pre>
  </div>
  <div id="progressbar" class="mt-progress mt-5"><div class="progress" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 100%;"></div></div></div>
  <div id="error-message-div" class="msg msg-error" style="display: none">
    <p class="msg-text alert alert-danger">
    <mt:if name="installing">
      <__trans phrase="Error during installation:">
    <mt:else>
      <__trans phrase="Error during upgrade:">
    </mt:if>
      <span id="error-message-text"></span>
    </p>
  </div>
  <form method="post" action="<mt:var name="script_url">" id="completed-action" style="display: none">
    <input type="hidden" name="__mode" value="redirect">
    <input type="hidden" name="token" id="redirect_token" value="">
  <mt:if name="installing">
    <input type="hidden" name="installed" value="1">
  </mt:if>
    <div class="actions-bar text-end mt-5">
      <button
         type="submit"
         accesskey="s"
         title="<mt:if name="installing"><__trans phrase="Sign in to Movable Type (s)"><mt:else><__trans phrase="Return to Movable Type (s)"></mt:if>"
         class="action primary button btn btn-primary">
      <mt:if name="installing">
        <__trans phrase="Sign in to Movable Type">
      <mt:else>
        <__trans phrase="Return to Movable Type">
      </mt:if>
      </button>
    </div>
  </form>
<mt:else>
  <p><__trans phrase="Your database is already current."></p>
  <form method="post" action="<mt:var name="mt_admin_url">">
    <div class="actions-bar text-end mt-5">
      <button
         type="submit"
         accesskey="s"
         title="<__trans phrase="Return to Movable Type (s)">"
         class="action primary button btn btn-primary">
        <__trans phrase="Return to Movable Type">
      </button>
    </div>
  </form>
</mt:unless>
</div>
</mt:setvarblock>

<mt:setvarblock name="js_include" append="1">
<mtapp:script path="js/tc.js">
<mtapp:script path="js/tc/client.js">
<mt:if name="use_jquery_json">
<mtapp:script path="jquery/jquery.json.js">
</mt:if>

<mt:unless name="up_to_date">
    <script>
    /* <![CDATA[ */
    function upgradeDone(success) {
        var progress = getByID("progressbar");
        if (progress) {
            progress.style.display = "none";
        }
        if (success) {
            var complete = getByID("completed-action");
            if (complete) {
                complete.style.display = "block";
            }
<mt:if name="installing">
            page_title.innerHTML = "<__trans phrase="Installation complete!">";
<mt:else>
            page_title.innerHTML = "<__trans phrase="Upgrade complete!">";
</mt:if>
        } else {
            var error = getByID("error-message-div");
            if (error) {
                error.style.display = "block";
            }
        }
    }

    var actionList = [];
<mt:if name="initial_steps">
    actionList = <mt:var name="initial_steps">;
</mt:if>

    function actionError(c, message) {
        alert( 'Error: ' + message );
    }

    var response_pos = 0;
    var upgrade_progress;
    var upgrade_container;
    function actionInteractive(c) {
        var responseText;
        try {
            responseText = c.responseText;
        } catch ( e ) {
            return;
        }
        if (!responseText) return;
        var text = responseText.substr(response_pos);
        text = text.replace(/\s*JSON:(.|\n)*/, '');
        // strip any partial lines. we'll grab 'em next time
        if (!text.match(/\n$/))
            text = text.replace(/(\r?\n)[^\r\n]*$/, '$1');
        response_pos += text.length;
        if (!text.length) return;

        text = text.replace(/\r?\n$/, '');

        var lines = text.split(/\r?\n/);
        for (var i = 0; i < lines.length; i++) {
            var line = lines[i];
            if (line.match(/ at .+ line \d+/)) { // ignore perlish stuff
                continue;
            }
            var matches = line.match(/^#([^ ]+?) (.*)/);
            if (matches && matches.length) {
                var id = matches[1];
                last_line = matches[2];
                var li = getByID(id);
                if (li) {
                    li.innerHTML = matches[2];
                } else {
                    li = document.createElement('li');
                    li.setAttribute('id', id);
                    li.appendChild(document.createTextNode(''));
                    li.innerHTML = matches[2];
                    upgrade_progress.appendChild(li);
                    scrollPanelDown(upgrade_container);
                }
            } else {
                matches = line.match(/^([^ ]+)/);
                if (matches && matches.length) {
                    last_line = line;
                    li = document.createElement('li');
                    li.appendChild(document.createTextNode(''));
                    li.innerHTML = line;
                    upgrade_progress.appendChild(li);
                    scrollPanelDown(upgrade_container);
                }
            }
        }
    }

    function scrollPanelDown(el) {
        el.scrollTop = el.scrollHeight;
    }

    function actionDone(c, result) {
        actionInteractive(c); // make sure our progress is up to date...
        if (result) {
            result = result.replace(/^(.|\n)*JSON:/, '');
            var response = eval('('+result+')');
            if (response.redirect) {
                const form = document.getElementById("completed-action");
                Object.keys(response.redirect).forEach(key => {
                    const input = document.getElementById("redirect_" + key);
                    input.setAttribute("value", response.redirect[key]);
                });
            }
            if (response.steps.length) {
                if (!response.error) {
                    actionList = response.steps;
                    setTimeout('runActions()',10);
                } else {
                    var err = getByID("error-message-text");
                    if (err) {
                        err.innerHTML = response.error;
                    }
                    upgradeDone(false);  // we got an error
                }
            } else {
                // we must be finished.
                upgradeDone(true);
            }
        }
    }

    function runActions(steps) {
        if (!actionList.length) return;
        // reset response_pos so we know where to pull from
        // for any interactive output...
        response_pos = 0;
        var actions = <mt:if name="use_jquery_json">jQuery.toJSON(actionList)<mt:else>JSON.stringify(actionList)</mt:if>;
        TC.Client.call({
            'load': actionDone,
            'interactive': actionInteractive,
            'error': actionError,
	        'method': 'POST',
            'uri': '<mt:var name="script_url">',
            'arguments': { '__mode' : 'run_actions',
<mt:unless name="installing">
                           'magic_token' : '<mt:var name="magic_token">',
<mt:else>
                           'installing' : '1',
</mt:unless>
                           'steps' : actions }
        });
    }
    jQuery(function() {
        upgrade_progress = jQuery('#upgrade-progress')[0];
        upgrade_container = jQuery('#upgrade-container')[0];
        page_title = jQuery('#page-title')[0];
        runActions();
    });
    /* ]]> */
    </script>
</mt:unless>
</mt:setvarblock>

<mt:include name="layout/chromeless.tmpl">
<mt:var name="layout">

