<?php

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

  IML DEPLOYMENT

  included functions for the act_*.php files

  ---------------------------------------------------------------------
  2013-11-08  Axel <axel.hahn@iml.unibe.ch>
  ###################################################################### */

global $aParams;
$aParams = array();


// ----------------------------------------------------------------------
// verifiy config
// ----------------------------------------------------------------------
    $aErrors=array();
    if (!isset($aConfig) || !is_array($aConfig)) {
        $aErrors[]="* \$aConfig does not exist. The config was not included before including " . __FILE__ . " in the request/ script.\n";
    } else {

        foreach (array(
            'appRootDir', 
            'configDir', 
            'workDir',
            'dataDir',
            'buildDir',
            'buildDefaultsDir',
            'packageDir',
            'archiveDir',
            ) as $sKey){
            if (!is_dir($aConfig[$sKey])){
                $aErrors[]="* \$aConfig['$sKey'] pints to a non existing directory (".$aConfig[$sKey].").\n";
            } else {
                if (!is_writable($aConfig[$sKey])){
                    $aErrors[]="* \$aConfig['$sKey'] = ".$aConfig[$sKey]." is NOT writable.\n";
                }
            }
        }
    }
        foreach (array(
            $aConfig['dataDir'].'/database', 
            $aConfig['dataDir'].'/projects', 
            $aConfig['dataDir'].'/sshkeys', 
            ) as $sDir2Check){
            if (!is_dir($sDir2Check)){
                $aErrors[]="* directory not found: $sDir2Check\n";
            } else {
                if (!is_writable($sDir2Check)){
                    $aErrors[]="* $sDir2Check is NOT writable.\n";
                }
            }
        }
    
        
    
    if (count($aErrors)){
        die("FATAL ERROR on config.<br>" . implode("<br>\n", $aErrors));
    }


// remark: $_SERVER does not exist in CLI
if (isset($_SERVER) && is_array($_SERVER) && array_key_exists("REQUEST_URI", $_SERVER)) {
    /*
      print_r($_GET);
      print_r($_POST);
      print_r($aParams);
      print_r($_SERVER);
      echo $_SERVER["REQUEST_URI"];
     */
    $aTmp = preg_split("#/#", $_SERVER["REQUEST_URI"]);
    if (count($aTmp) > 1 && $aTmp[1] == "deployment" && $aTmp[2] != "?") {
        array_shift($aTmp);
        array_shift($aTmp);
        if (
                count($aTmp) && $aTmp[count($aTmp) - 1] && $aTmp[count($aTmp) - 1][0] == "?"
        ) {
            array_pop($aTmp);
        }
        if (count($aTmp) && $aTmp[0])
            $aParams["prj"] = $aTmp[0];
        if (count($aTmp) > 1 && $aTmp[1])
            $aParams["action"] = $aTmp[1];
        if (count($aTmp) > 2 && $aTmp[2])
            $aParams["par3"] = $aTmp[2];
        if (count($aTmp) > 3 && $aTmp[3])
            $aParams["par4"] = $aTmp[3];
    }
    if (count($_GET))
        foreach ($_GET as $key => $value)
            $aParams[$key] = $value;
    if (count($_POST))
        foreach ($_POST as $key => $value)
            $aParams[$key] = $value;

    /* force integer params
      foreach (array("id") as $sKey) {
      if (array_key_exists($sKey, $aParams)) {
      $aParams[$sKey]=(int)$aParams[$sKey];
      }
      }
     */

    foreach (array_keys($aParams) as $sKey) {
        $aParams[$sKey] = str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $aParams[$sKey]);
    }
}
$sImageBase = "/deployment/images/nuvola64x64/";
$aImages = array(
    'overview' => 'apps/fsview.png',
    'project' => 'filesystems/desktop.png',
    'action' => 'apps/aktion.png',
    'build' => 'apps/kthememgr.png',
);

/**
 * get home link as button
 * @return string
 */
function aHome($sClass = "btn btn-default") {
    global $aParams;
    // if (!array_key_exists("prj", $aParams)) return false;
    return '<a href="/deployment/?" class="' . $sClass . '"><i class=" glyphicon glyphicon-home"></i> ' . t("menu-overview") . '</a>';
}

/**
 * get project Home link as button
 * @return string
 */
function aPrjHome($sClass = "btn btn-default") {
    global $aParams, $aConfig;
    if (!array_key_exists("prj", $aParams))
        return false;
    if ($aParams["prj"] == "all")
        return aHome($sClass);
    // if (!array_key_exists("action", $aParams)) return false;

    require_once("./classes/project.class.php");
    $oPrj = new project($aParams["prj"]);
    return '<a href="/deployment/' . $aParams["prj"] . '/" class="' . $sClass . '"><i class=" glyphicon glyphicon-book"></i> ' . t("menu-project-home") . ' <strong>' . $oPrj->getLabel() . '</strong></a>';
}

/**
 * get go top link as button
 * @return string
 */
function aGotop($sClass = "scroll-link btn btn-default") {
    return '<a href="#top" class="' . $sClass . '" title="' . t("gotop") . '"><i class=" glyphicon glyphicon-eject"></i> </a> ';
}

/**
 * auto generate upper part of the page with header and navigation 
 * @global type $aParams
 * @return type
 */
function getTopArea() {
    global $aParams, $sImageBase, $aImages, $aConfig;
    $sReturn = '';
    require_once("./classes/project.class.php");
    require_once("./classes/user.class.php");
    $oUser = new user();

    $sMyPhase = "[phase]";
    $sMyRev = " [no rev] ";
    $sJsonfile = $_SERVER["DOCUMENT_ROOT"] . "ci-webgui.json";
    if (file_exists($sJsonfile)) {
        $aJson = json_decode(file_get_contents($sJsonfile), true);
        if (array_key_exists("date", $aJson))
            $sMyRev = $aJson["date"];
    }

    $sBaseUrl = '/deployment/';
    $sWikiBaseUrl = 'https://secure.iml.unibe.ch/wiki/doku.php';
    $sReturn = '
        <span id="top"></span>
        <nav class="navbar navbar-inverse" role="navigation">
          <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class=" glyphicon glyphicon-bar"></span>
                <span class=" glyphicon glyphicon-bar"></span>
                <span class=" glyphicon glyphicon-bar"></span>
              </button>
              <nobr>
                <a class="navbar-brand" href="' . $sBaseUrl . '"><span class="glyphicon glyphicon-home"></span> '.t("menu-brand").'</a>
                <span class="badge"></span>
              </nobr>
              &nbsp;&nbsp;&nbsp;
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            ';
    if($oUser->getUsername()){
        $sReturn.='
              <ul class="nav navbar-nav">
              
                <li class="dropdown';
                if (!array_key_exists("prj", $aParams)){
                    $sReturn.=' active';
                }
                $sReturn.='">'
                        . '<a href="' . $sBaseUrl . '" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"
                  >'.t("menu-overview").' <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="' . $sBaseUrl . 'all/setup/">' . t("menu-settings") . '</a></li>
                    <li><a href="' . $sBaseUrl . 'all/setup/actionlog/">' . t("menu-logs") . '</a></li>
                    <li><a href="' . $sBaseUrl . 'all/setup/new/">' . t("menu-new-project") . '</a></li>
                  </ul>
                </li>
                

                <li class="dropdown">
                   <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"
                   >' . t("menu-projects") . ' <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    ';
                
                    $oPrj1 = new project();
                    foreach ($oPrj1->getProjects() as $sPrj) {
                        $oPrj = new project($sPrj);
                        $sReturn.='<li><a href="' . $sBaseUrl . $sPrj . '/">' . $oPrj->getLabel() . '</a></li>';
                    }
                    $sReturn.='
                  </ul>
                </li>
              ';

                if (array_key_exists("prj", $aParams) && $aParams["prj"] <> "all") {
                    $oPrj = new project($aParams["prj"]);
                    $sReturn.='
                                <li class="active">' . aPrjHome(" ") . '</li>
                                ';
                    if (array_key_exists("action", $aParams) and FALSE) {
                        $sReturn.='<li><a href="#">Aktion: ' . $aParams["action"] . '</a></li>';
                    } else {
                        $sReturn.='
                                    <li class="dropdown">
                                        <a href="' . $sBaseUrl . '" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"
                                        >'.t("menu-project-actions").' <span class="caret"></span></a>

                                    <ul class="dropdown-menu" role="menu">
                                        <!--
                                        <li><a href="' . $sBaseUrl . $aParams["prj"] . '/build/">' . t("menu-project-build") . '</a></li>
                                        -->
                                        <li><a href="' . $sBaseUrl . $aParams["prj"] . '/setup/">' . t("menu-project-settings") . '</a></li>
                                        <li><a href="' . $sBaseUrl . $aParams["prj"] . '/cleanup/">' . t("menu-project-cleanup") . '</a></li>
                                        <li><a href="' . $sBaseUrl . $aParams["prj"] . '/delete/">' . t("menu-project-delete") . '</a></li>
                                    ';
                        $sReturn.='</ul></li>';

                        $aPhases = $oPrj->getActivePhases();
                        if (count($aPhases)) {
                            $sReturn.='<li class="dropdown"">
                                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">' . t("menu-project-phases") . '<b class="caret"></b></a>
                                            <ul class="dropdown-menu"  role="menu">';
                            foreach ($aPhases as $sPhase) {
                                $sReturn.='<li><a href="' . $sBaseUrl . $aParams["prj"] . '/phase/' . $sPhase . '/">' . $sPhase . '</a></li>';
                            }
                            $sReturn.='</ul></li>';
                        }
                    }
                }
    }
                    
            $sReturn.='
              </ul>
            
            <ul class="nav navbar-nav navbar-right">
                    <!-- userdata -->
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"
                        ><span class="glyphicon glyphicon-user"></span> ' . $oUser->getUsername() . ' <b class="caret"></b></a>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="' . $sBaseUrl . 'all/login/">' . t("menu-login") . '</a></li>
                        </ul>
                    </li>


                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"
                        ><span class="glyphicon glyphicon-question-sign"></span> ' . t("menu-help") . ' <b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li><a href="' . $sWikiBaseUrl . '/it/entwicklung/continuous_deployment">WIKI: Übersicht Continous Deployment</a></li>
                            <li><a href="' . $sWikiBaseUrl . '/it/entwicklung/continuous_deployment#konventionen">WIKI: Konventionen für Entwickler</a></li>
                            <li><a href="' . $sWikiBaseUrl . '/it/infrastruktur/dienste/puppet/snippets#iml-deployment">WIKI (Admin): Puppet-Snippets für den Sysadmin</a></li>
                            <li><a href="' . $sWikiBaseUrl . '/it/infrastruktur/dienste/imldeployment">WIKI (Admin): Verzeichnisse und Dateien</a></li>
                            <li><a href="/deployment/all/doc/">' . t("menu-help-classes") . '</a></li>
                        </ul>
                    </li>
            </ul>
            </div><!-- /.navbar-collapse -->
          </div><!-- /.container-fluid -->
        </nav>    
         
          <span id="swversion">' . $sMyRev . ' @ ' . php_uname("n") . '</span>
        </div><div id="header2">';

    if (!array_key_exists("prj", $aParams)) {
        $sReturn.='<!-- <img src="' . $sImageBase . $aImages['overview'] . '" id="imgtop" alt=""> -->'
                . '<h1>' . t("overview-label") . '</h1><span class="description">' . t("overview-hint") . '</span>';
    } else {
        if ($aParams["prj"] <> "all") {
            $oPrj = new project($aParams["prj"]);
            $sReturn.='<!-- <img src="' . $sImageBase . $aImages['project'] . '" id="imgtop" alt="">-->
                <h1>' . $oPrj->getLabel() . '</h1><span class="description">' . $oPrj->getDescription() . '</span>';
            if (array_key_exists("action", $aParams)) {
                // $sReturn.='<h2>Aktion: '.$aParams["action"].'</h2>';
            }
        }
    }
    $sReturn.='</div>';

    return $sReturn;
}

/**
 * get h2 headline with action
 * @global type $aParams
 * @global string $sImageBase
 * @global array $aImages
 * @return string
 */
function getAction() {
    global $aParams, $sImageBase, $aImages;
    $sReturn = '';
    if (array_key_exists("action", $aParams)) {
        $sLabel = $aParams["action"];
        if (array_key_exists("par3", $aParams)) {
            $sLabel.=' :: ' . $aParams["par3"];
        }
        $sReturn.='<h2 class="action ' . $aParams["action"] . '">' . $sLabel . '</h2>';
    } else if (array_key_exists("prj", $aParams)) {
        $sReturn.='<h2 class="action prjhome"> Projekt-Home</h2>';
    }
    return $sReturn;
}

/**
 * translate function
 * @global type $aConfig
 * @staticvar array $aLang
 * @param string $s text
 * @return string
 */
function t($s) {
    global $aConfig;
    static $aLang = array();

    if (!is_array($aConfig) || !array_key_exists("lang", $aConfig)) {
        die("ERROR: \$aConfig[\"lang\"] does not exist.\n");
    }
    if (!count($aLang)) {
        $sLangfile = __DIR__ . "/../../config/lang/" . $aConfig["lang"] . ".json";
        if (!file_exists($sLangfile)) {
            die("language file was not found: $sLangfile");
        }
        $aLang = json_decode(file_get_contents($sLangfile), true);
    }

    if (!array_key_exists($s, $aLang)) {
        return '<span class="warning">' . $s . '</span>';
    }
    // return $aLang[$s].' ('.$s.')';
    return $aLang[$s];
}

/**
 * enter user and comment 
 * @global type $aParams
 * @return string
 */
function enterDeployinfos() {
    global $aParams;
    $sIdUser = "inputUser";
    $sIdComment = "inputComment";
    $sUser = (array_key_exists($sIdUser, $aParams)) ? $aParams[$sIdUser] : "";
    $sComment = (array_key_exists($sIdComment, $aParams)) ? $aParams[$sIdComment] : "";

    $sOut = '
        <div class="control-group">
            <label class="control-label" for="inputUser">Benutzername</label>
            <div class="controls">
                <input type="text" id="inputUser" name="inputUser" placeholder="Benutzername" value="' . $sUser . '">
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="inputComment">Kommentar zum Deployment</label>
            <div class="controls">
                <textarea id= rows="3" id="inputComment" name="inputComment" placeholder="Kommentar">' . $sComment . '</textarea>
            </div>
        </div>
        ';

    return $sOut;
}