<?php

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

  IML DEPLOYMENT

  webgui - setup
    * for a new project
    * settings of the current project

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

require_once("./classes/project.class.php");
require_once("./inc_functions.php");
$sOut = '';

$sFakePassword='********************';

// items to mask
$aMask=array(
    'auth'=>array(
        'ldap'=>array(
            'PwLdapUser'=>$sFakePassword
        )
    ),
    'foreman'=>array(
        'password'=>$sFakePassword
    ),
    'projects'=>array(
        'ldap'=>array(
            'PwLdapUser'=>$sFakePassword
        )
    ),
);

/**
 * hide entries in config array
 * @param type $aMask
 * @param type $aConfig
 * @return type
 */
function maskEntries($aMask, $aConfig){
    foreach ($aMask as $sKey=>$aValue){
        
        if (array_key_exists($sKey, $aConfig)){
            $aConfig[$sKey]=(is_array($aValue)
                    ? maskEntries($aMask[$sKey], $aConfig[$sKey])
                    : $aMask[$sKey]
            )
            ;
        }
    }
    return $aConfig;
}

if ($aParams["prj"] == "all") {
    
    // ------------------------------------------------------------
    // general setup - overview
    // ------------------------------------------------------------
    if (!array_key_exists("par3", $aParams)) {
        $oPrj = new project();
        $aTmp=maskEntries($aMask, $aConfig);
        $sOut.= '<pre>'.print_r($aTmp, 1).'</pre>';
        
        // print_r($aConfig);
        $i = 0;
        require_once ("./classes/formgen.class.php");
        
        // define editable options
        $aMapping=array(
            'general'=>array(
                '["workDir"]'=>array('type'=>'text'),
                '["versionsToKeep"]'=>array('type'=>'text', 'validate'=>'isinteger'),
                '["builtsToKeep"]'=>array('type'=>'text', 'validate'=>'isinteger'),
                '["lang"]'=>array('type'=>'text'),
            ),
            'install'=>array(
                '["installPackages"]["user"]'=>array('type'=>'text'),
                '["installPackages"]["addkeycommand"]'=>array('type'=>'text'),
                '["installPackages"]["testcommand"]'=>array('type'=>'text'),
                '["installPackages"]["command"]'=>array('type'=>'text'),
            ),
        );
        foreach ($aConfig['phases'] as $sPhase => $aPhaseData){
            $aMapping['phase-'.$sPhase]=array(
                '["phases"]["'.$sPhase.'"]["css"]["bgdark"]'=>array('type'=>'text'),
                '["phases"]["'.$sPhase.'"]["css"]["bglight"]'=>array('type'=>'text'),
                '["phases"]["'.$sPhase.'"]["css"]["bgbutton"]'=>array('type'=>'text'),
            );
            /*
            if (array_key_exists("deploytimes", $aConfig["phases"][$sPhase])){
                $aMapping['phase-'.$sPhase]['["phases"]["'.$sPhase.'"]["deploytimes"]']=array('type'=>'text');
            }
             * 
             */
        }
        
        $aForms = array(
            'setup' => array(
                'meta' => array(
                    'method' => 'POST',
                    'action' => '?',
                ),
                'validate' => array(),
                'form' => array(
                    'input' . $i++ => array(
                        'type' => 'hidden',
                        'name' => 'setupaction',
                        'value' => 'save',
                    ),
                ),
            )
        );
        foreach ($aMapping as $sPartname=>$aPartData){
            
            // add a headline
            $aForms['setup']['form']['input' . $i++] = array(
                'type' => 'markup',
                'value' => '<h3>'.t('setup-deployment-'.$sPartname).'</h3>',
            );
            
            // add input items
            foreach ($aPartData as $sName=>$aFormOptions){
                
                $sEval='$sCfgVal=$aConfig'.$sName.';';
                eval($sEval);
                
                // checks
                if (!$sCfgVal){
                    $sError.='<li>configration variable $sConfig'.$sName.' does not exist.</li>';
                }
                // echo $sEval . ' .. ' . $sName . " :: " . $sCfgVar."<br>";
                $sFormname=str_replace('"', '' , 'aConfig'.$sName);

                
                $aForms['setup']['form']['input' . $i++] = array(
                    'value' => '<h3>'.t('setup-deployment-'.$sPartname).'</h3>',
                    'type' => $aFormOptions['type'],
                    'name' => $sFormname,
                    'label' => 'aConfig'.$sName,
                    'value' => $sCfgVal,
                    // 'required' => 'required',
                    'validate' => 'isastring',
                    'title' => htmlentities($sCfgVal),
                    'size' => 100,
                    'placeholder' => htmlentities($sCfgVal),
                );
            }
        }
        if ($sError){
            $sOut.=$oHtml->getBox("error", '<ul>'.$sError.'</ul>');
        } else {
            $oForm = new formgen($aForms);
            // TODO: unhide after checkin
            // $sOut.=$oForm->renderHtml("setup");
        }
        
    }
        
    if (array_key_exists("par3", $aParams)) {
        
        // ------------------------------------------------------------
        // setup a new project
        // ------------------------------------------------------------
        if ($aParams["par3"]=="new") {
            $sOut.='<h2>'.t("page-setup-info-new-project").'</h2>'
                    . '<p>'.t("page-setup-info-new-project-introtext").'</p><hr>';
            $oPrj = new project();

            if (array_key_exists("setupaction", $aParams) && $aParams["setupaction"] == "create") {
                $sError = $oPrj->create($aParams["id"]);
                if (!$sError) {
                    header("location: /deployment/" . $aParams["id"] . "/setup/");
                }
                $sOut.=$oHtml->getBox("error", $sError);
            }
            $sOut.=$oPrj->renderNewProject();
        }
        // ------------------------------------------------------------
        // users and roles
        // ------------------------------------------------------------
        /*
        if ($aParams["par3"]=="users") {
            $sOut.='<h2>'.t("page-setup-info-users-and-roles").'</h2>'
                    . '<p>'.t("page-setup-info-users-and-roles-introtext").'</p><hr>';
            
            $oUserCfg=new user();
            $aUser2Roles=$oUserCfg->getUser2Roles();
            // $aUser2Projects=$oUserCfg->getUser2Projects();
            
            $aUsers=array();
            $sOut.=print_r($aUser2Roles,1).'<br>';
            $sRoles='';
            foreach ($aUser2Roles as $sRole=>$aUserlist){
                $sRoles.='<strong>'.$sRole.'</strong><br>';
                if (count($aUserlist)){
                    foreach ($aUserlist as $aUseritem){
                        $aUsers[$aUseritem]=1;
                        $sRoles.='<span class="user user-'.md5($aUseritem).'">'.$aUseritem.'</span> | ';
                    }
                } else {
                    $sRoles.='---';
                }
                $sRoles.='<br><br>';
            }
            
            $sUsers='';
            foreach(array_keys($aUsers) as $aUseritem){
                $sUClass='.user-'.md5($aUseritem);
                $sUsers.='<a href="#" onclick="$(\''.$sUClass.'\').css(\'background\', \'#fe8\');">'.$aUseritem.'</a>';
            }
            $sOut.=$sUsers . $sRoles;
        }
         * 
         */
        // ------------------------------------------------------------
        // check lang-texts
        // ------------------------------------------------------------
        if ($aParams["par3"]=="checklang") {
            $sOut.='<h2>'.t("page-setup-info-check-lang").'</h2>'
                    .'<p>'.t("page-setup-info-check-lang-intro").'</p>';
            // $sOut.=print_r($aConfig, true);
            $aTmp=array();
            $aLangs=array();
            
            // --- fetch data
            foreach (glob($aConfig["configDir"] . '/lang/*.json') as $filename) {
                $sLang=basename($filename);
                $aLangs[]=$sLang;
                foreach (json_decode(file_get_contents($filename), true) as $skey => $sText){
                    $aTmp[$skey][$sLang]=$sText;
                }
            }
            
            // --- generate output
            $sWarnings='';
            $sErrors='';
            $sTable.='<table class="table"><thead><tr>'
                    . '<th>key</th>';
                foreach ($aLangs as $sLang) {
                    $sTable.='<th>'.$sLang.'</th>';
                }
            $sTable.='</tr></thead><tbody>';
            
            foreach ($aTmp as $sKey => $aTexts){
                $trid='tr'.md5($sKey);
                $sTable.='<tr id="'.$trid.'"><td>'.$sKey.'</td>';
                foreach ($aLangs as $sLang) {
                    if (array_key_exists($sLang, $aTmp[$sKey])){
                        if (!$aTmp[$sKey][$sLang]){
                            $sWarnings.='<li><a href="#'.$trid.'">'.$sLang.': key <em>'.$sKey.'</em> is empty.</a></li>';
                            $sTable.='<td>'.t("empty").'</td>';
                        } else {
                            $sTable.='<td>'.htmlentities($aTmp[$sKey][$sLang]).'</td>';
                        }
                    } else {
                        $sErrors.='<li><a href="#'.$trid.'">'.$sLang.': key <em>'.$sKey.'</em> does not exist.</a></li>';
                        $sTable.='<td class="error">!!! MISS !!!</td>';
                    }
                }
                $sTable.='</tr>';
            }
            $sTable.='</tbody></table>';
            if ($sWarnings)$sWarnings='<ol class="warning">'.$sWarnings.'</ol>';
            if ($sErrors)$sErrors='<ol class="error">'.$sErrors.'</ol>';
            $sOut.=$sErrors.$sWarnings.$sTable;
        }
        // ------------------------------------------------------------
        // logoanalyzer
        // ------------------------------------------------------------
        // TODO
        if ($aParams["par3"]=="actionlog") {
            // $oPrj = new project();
            require_once("./classes/actionlog.class.php");
            $oLog=new Actionlog('');
            
            $sOut.=$oLog->renderLogs(array(), true);
            
        }
        
    }
    
} else {

    // ------------------------------------------------------------
    // setup page of a an existing project
    // ------------------------------------------------------------
    $oPrj = new project($aParams["prj"]);
    // $sOut.='<div style="float: right">aParams:<pre>'.print_r($aParams, true).'</pre></div>';

    if (array_key_exists("setupaction", $aParams) && $aParams["setupaction"] == "save") {
        if ($oPrj->saveConfig()) {
            $sOut.=$oHtml->getBox("success", t("page-setup-info-settings-were-saved"));
        } else {
            $sOut.=$oHtml->getBox("error", t("page-setup-error-settings-were-not-saved"));
        }
    }

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

// -- Ausgabe
echo $sOut;
