<?php

/* ######################################################################

  IML DEPLOYMENT

  webgui - build a package

  ---------------------------------------------------------------------
  2014-11-14  Axel <axel.hahn@iml.unibe.ch>  selector for branches
  2014-02-14  Axel <axel.hahn@iml.unibe.ch>  build was "ajaxified"
  2013-11-08  Axel <axel.hahn@iml.unibe.ch>
  ###################################################################### */

require_once("./classes/project.class.php");
require_once("./classes/formgen.class.php");

// --- Checks
$oPrj = new project($aParams["prj"]);

$sOut = '';

// switch to a branch if it was selected
$sBranchname = '';
if (array_key_exists("branchname", $aParams)) {
    $sBranchname = $aParams["branchname"];
    $oPrj->setBranchname($aParams["branchname"]);
} else {
    $sBranchname = $oPrj->getBranchname();
}

if (!array_key_exists("confirm", $aParams)) {
    // ------------------------------------------------------------
    // let the user click a button to make a new build
    // ------------------------------------------------------------
    $sNext = $oPrj->getNextPhase();
    $aPhaseData2 = $oPrj->getPhaseInfos($sNext);

    $sOut.='<p>' . sprintf(t("page-build-info"), $sNext, $sNext) . '</p>';

    $sRevison = false;
    $aRepodata = $oPrj->getRepoRevision();
    if (array_key_exists("revision", $aRepodata)) {
        $sRevison = $aRepodata["revision"];
        if (
                array_key_exists("revision", $aPhaseData2["onhold"]) && $aPhaseData2["onhold"]["revision"] == $sRevison
        ) {
            $sOut.=$oHtml->getBox("warning", "In der Queue von [$sNext] ist die Version bereits $sRevison vorhanden!");
        }
        if (
                array_key_exists("revision", $aPhaseData2["ready2install"]) && $aPhaseData2["ready2install"]["revision"] == $sRevison
        ) {
            $sOut.=$oHtml->getBox("warning", "Im Repo von [$sNext] ist die Version $sRevison bereits vorhanden!");
        }
    }
    $sOut.='
        <table>
             <thead>
                 <tr>
                     <th class="versioncontrol" colspan="2">' . $oHtml->getIcon('repository').t("versioncontrol") . '<br></th>
                     <th> </th>
                     <th class="' . $sNext . '" colspan="2">' . $oHtml->getIcon('phase').$sNext . '</th>
                 </tr>
             </thead>
             <tbody>
                 <tr>
                     <td class="">
                         ' . $oPrj->renderSelectRemoteBranches() . '
                     </td>
                     <td class="">
                         ' . $oPrj->renderRepoInfo() . '
                     </td>
                     <td style="vertical-align: middle;">
                         <img src="/deployment/images/nuvola64x64/apps/noatun.png" alt="arrow to the right">
                     </td>
                     <td class="' . $sNext . '">
                         ' . t("onhold") . ':<br>
                         ' . $oPrj->renderPhaseDetail($sNext, "onhold", false) . '
                     </td>
                     <td class="' . $sNext . '">
                         ' . t("ready2install") . ':<br>
                         ' . $oPrj->renderPhaseDetail($sNext, "ready2install", false) . '
                     </td>
                 </tr>
                 </tbody>
        </table>
        <br>
        ';

    // Eingabe Kommentare zum Deployment
    if ($sRevison) {
        $sOut.='
                 <form action="?" method="post" enctype="multipart/form-data">
                    <input type="hidden" name="confirm" value="1">
                    <input type="hidden" name="branchname" value="' . $sBranchname . '">
                    <!-- ' . enterDeployinfos() . '
                     <hr>
                    -->
                    <fieldset>
                        '.aGoback().'
                        <button type="submit" class="btn btn-primary btn-large" >' . sprintf(t("page-build-buttonlabel"), $sNext) . '</button>
                    </fieldset>
                 </form>
                 ';
    }
} else {
    // ------------------------------------------------------------
    // start new build
    // ------------------------------------------------------------
    $sOutDir = sys_get_temp_dir();

    // action run: start action as background process
    // it will be initialized with jQuery $.post( "' . $sUrlStartAction . '" ... )
    // see a few lines below

    if (array_key_exists("run", $aParams)) {
        echo $oPrj->build($sOutDir . "/" . $aParams["ajax"]);
        die();
    }

    // the ajax polling request reads tmpfile
    // read produced content from tempfile
    // remark: this part was moved to ../webservice/getfile.php
    /*
    if (array_key_exists("ajax", $aParams)) {
        $sLine = "<h2 class=\"warning\">" . t("page-build-info-processing") . "</h2>";
        $sProcesses = t("page-build-info-load") . ": "
                . shell_exec("uptime")
                . "<br>" . t("page-build-info-processes") . ":<pre>"
                . shell_exec("ps -f | fgrep -v apache | fgrep -v 'ps -f' | fgrep -v fgrep")
                . "</pre>";
        $sTmpFile = $sOutDir . "/" . $aParams["ajax"];
        $sOut = file_exists($sTmpFile) ? file_get_contents($sTmpFile) : "";

        echo $sLine . $sProcesses;
        if ($sOut) {
            echo '<div style="margin-left: 3em; border-left: 5px dotted #eee; padding-left: 1em;">'
            . $sOut . '</div><div style="clear: both;"></div>' . $sLine;
        }
        die();
    }
     */

    // html code after pressing build button:
    // initiate one request to start the build and one to fetch preocess output
    // $sTmpFile = basename(tempnam("", "out_".$aParams["prj"]."_".$aParams["action"])."_");
    $sAjaxFile = $aParams["prj"] . "_" . $aParams["action"];
    $sDivname = "outAjax";
    $sUrlStartAction = "/deployment/?"
            . "&prj=" . $aParams["prj"]
            . "&action=" . $aParams["action"]
            . "&confirm=" . $aParams["confirm"]
            . "&branchname=" . $aParams["branchname"]
            . "&ajax=" . $sAjaxFile
            . "&run=1"
    ;
    $sUrlFile = "/webservice/getfile.php?". "&ajax=" . $sAjaxFile;
    
    $sOut.= '<div id="' . $sDivname . '"></div>'
            . '<script>
                    var iRepeat=3000;
                    
                    // start build process
                    $.post( "' . $sUrlStartAction . '", function( data ) {
                        $( "#' . $sDivname . '" ).html( data );
                        iRepeat=false; // stop polling if build is finished
                    });

                    // polling result during progress...
                    function AjaxPolling(sUrl, sDivname){
                        if (!iRepeat) return false;
                        $.post( sUrl, function( data ) {
                            if (iRepeat) {
                                    $("#"+sDivname ).html( data );
                            }
                        });
                        if (iRepeat){
                            window.setTimeout("AjaxPolling( \'"+sUrl+"\', \'"+sDivname+"\', \'"+iRepeat+"\')", iRepeat);
                        }
                    }
                    
                    // init polling
                    AjaxPolling("' . $sUrlFile . '", "' . $sDivname . '");

            </script>';
}

$sOut.= '<div id="navbuttom">' . aPrjHome() . '</div>';

// -- Ausgabe
echo $sOut;
