<?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_gui.class.php");
require_once("./classes/formgen.class.php");
set_time_limit(0);

// --- Checks
$oPrj = new projectgui($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);
    $sBranchontarget = isset($aPhaseData2["ready2install"]["branch"]) ? $aPhaseData2["ready2install"]["branch"] : '';
    print_r($sBranchname);
    $bIgnoreCache = isset($aParams['reloadBranches']) ? $aParams['reloadBranches'] : false;

    // $sOut.='<p>Re-Read Branches (ignore caching) - '.($bIgnoreCache ? "JA" : "mein" ).'</p>';

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

    $sRevison = false;
    $aRepodata = $oPrj->getRepoRevision(true);
    if (isset($aRepodata["revision"])) {
        $sRevison = $aRepodata["revision"];
        if (
            array_key_exists("revision", $aPhaseData2["onhold"]) && $aPhaseData2["onhold"]["revision"] == $sRevison
        ) {
            $sOut .= $oHtml->getBox("warning", sprintf(t("page-build-warning-version-exists"), $sNext, $sRevison));
        }
        if (
            array_key_exists("revision", $aPhaseData2["ready2install"]) && $aPhaseData2["ready2install"]["revision"] == $sRevison
        ) {
            $sOut .= $oHtml->getBox("warning", sprintf(t("page-build-warning-version-is-installed"), $sNext, $sRevison));
        }
    }
    $sOut .= '
        <table>
             <thead>
                 <tr>
                     <th class="versioncontrol" colspan="3">' . $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(false, $bIgnoreCache) . '
                         ' . (
        $sBranchontarget && $sBranchontarget != $sBranchname
        ? '
                             <form action="?" method="post" enctype="multipart/form-data">
                                 <input type="hidden" name="reloadBranches" value="1">
                                 <input type="hidden" name="branchname" value="' . $sBranchontarget . '">
                                    ' . sprintf(t('page-build-branch-on-target'), $sBranchontarget) . '<br>
                                     <button type="submit" class="btn btn-default">' . sprintf(t('page-build-switch-to-target'), $sBranchontarget) . '</button>
                             </form>
                             <br><hr>
                             '
        : ''
    ) . '
                          <form action="?" method="post" enctype="multipart/form-data">
                            <input type="hidden" name="reloadBranches" value="1">
                            <input type="hidden" name="branchname" value="' . $sBranchname . '">
                            <fieldset>
                                <button type="submit" class="btn btn-default">' . $oHtml->getIcon('refresh') . t("page-build-reload-branches") . '</button>
                            </fieldset>
                        </form>
     
                    </td>
                     <td>&nbsp;&nbsp;&nbsp;</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-large ' . $sNext . '" >' . $oHtml->getIcon('build') . sprintf(t("page-build-buttonlabel"), $sNext) . '</button>
                    </fieldset>
                 </form>
                 ';
    }
    $BODY =
        $renderAdminLTE->addRow(
            $renderAdminLTE->addCol(
                $renderAdminLTE->getCard([
                    'type' => 'success',
                    'variant' => 'outline',
                    'text' => $sOut,
                ]),
                12
            )
        );

} 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=2000;
                    
                    // 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;