<?php

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

  IML DEPLOYMENT

  webgui - shows build versions in all places (onhold, ready2install, deployed)
  of a given phase.

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

require_once("./classes/project.class.php");
require_once("./inc_functions.php");
require_once("./classes/config-replacement.class.php");


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

$sOut = '';
if (array_key_exists("par3", $aParams)) {
    $sPhase = $aParams["par3"];
}

if ($sPhase) {
    $aWarnings=array();
    $sOutReplace='';
    
    // ----------------------------------------------------------------------
    // replacement
    // ----------------------------------------------------------------------
    
    $oConfig = new configreplacement();
    $oConfig->setProject($aParams["prj"], $sPhase);

    $aReplacements=$oConfig->getReplacements();

    $sOut.='<h3>' . $oHtml->getIcon('replace') . t("replacements") . '</h3>';

    // ----------------------------------------------------------------------
    // Links to foreman
    // ----------------------------------------------------------------------
    $aForeman=$oConfig->getForemanReplacements();
    $aReplacementsForeman=$aForeman ? $aForeman['rules'] : false;
    
    // echo '<pre>$aReplacements = '.print_r($aReplacements, 1) . '</pre>';
    // echo '<pre>$aForeman = '.print_r($aForeman, 1) . '</pre>';

    $sOut.=($aForeman
            ? $oConfig->getForemanlink2Hostgroup().' '
                .$oConfig->getForemanlink2Host()
            : t('foreman-no-host')
            ).'<br><br>'
        ;

    // ----------------------------------------------------------------------
    // Loop over files
    // ----------------------------------------------------------------------

    if ($aReplacements) {
        
        // open all/ close all
        if(count($aReplacements)>1){
            $sOutReplace.=$oHtml->getLinkButton(array(
                'onclick'=>'$(\'.divfileinfos\').slideDown(); $(\'.expandable\').removeClass(\'closed\'); this.blur(); return false;',
                'icon'=>'fa-chevron-down',
            ))
            .$oHtml->getLinkButton(array(
                'onclick'=>'$(\'.divfileinfos\').slideUp(); $(\'.expandable\').addClass(\'closed\'); this.blur(); return false;',
                'icon'=>'fa-chevron-up',
            ))
            ;
        }
        
        foreach ($aReplacements as $sFile => $aFields) {
            $tTplFile = basename($sFile);
            $bFileInForeman = $aReplacementsForeman && array_key_exists($tTplFile, $aReplacementsForeman);
            $sDivIdFile='div4file-'.md5($sFile);

            $sOutReplace.='<h4>' . 
                    $oHtml->getLink(array(
                        'onclick'=>'$(\'#'.$sDivIdFile.'\').slideToggle(); $(this).toggleClass(\'closed\'); return false;',
                        'class'=>'expandable closed',
                        'icon'=>'templatefile',
                        'label'=>$tTplFile,
                    )) . '</h4>'
                    . '<div id="'.$sDivIdFile.'" class="divfileinfos" style="display: none;">'
                    ;

            // --- check: does this file in foreman exist?
            if (!array_key_exists($tTplFile, $aReplacementsForeman)){
                if ($aReplacementsForeman){
                    $sOutReplace.=$oHtml->getBox('error', t('foreman-error-template-unknown'));
                    $aWarnings[]=$tTplFile.': '.t('foreman-error-template-unknown');
                }
            }


            // --- check: target file was set?
            $aTable=array('header'=>array(), 'body'=>array());
            if ($bFileInForeman){
                if ($aReplacementsForeman && array_key_exists('target', $aReplacementsForeman[$tTplFile])){
                    $sTd='<strong>'.$oHtml->getIcon('targetfile') . $aReplacementsForeman[$tTplFile]['target'].'</strong>';
                } else {
                    if ($bFileInForeman){
                        $sTd=t('foreman-error-no-target');
                        $aWarnings[]=$tTplFile.': '.t('foreman-error-no-target');
                    } else {
                        $sTd='-';
                    }
                }
                $aTable['body'][]=array(
                    $oHtml->getIcon('templatefile') . t('foreman-targetfile'), 
                    $sTd
                );
            }

            // --- loop over all replacement items of template file
            //     and check if they exist in foreman
            if (count($aFields)) {
                foreach ($aFields as $sField){
                    if ($aReplacementsForeman && array_key_exists($sField, $aReplacementsForeman[$tTplFile]['replace'])){
                        $sTd=$aReplacementsForeman[$tTplFile]['replace'][$sField];
                    } else {
                        if ($bFileInForeman){
                            $sTd=$oHtml->getBox('error', sprintf(t('foreman-error-no-replacement-for-id'), $sField));
                            $aWarnings[]=$tTplFile.': '.sprintf(t('foreman-error-no-replacement-for-id'), $sField);
                        } else {
                            $sTd='-';
                        }

                    }
                    $aTable['body'][]=array(
                        $oHtml->getIcon('replace') . $sField, 
                        $sTd
                    );
                }
            } else {
                $aTable['body'][]=array(
                    $oHtml->getBox('error', t('foreman-error-no-replacement-in-templatefile')),
                    '-'
                );
                $aWarnings[]=$tTplFile.': '.t('foreman-error-no-replacement-in-templatefile');
            }

            // --- reverse check ... loop over all replacement items of foreman
            //     and check if they exist in template
            if ($aReplacementsForeman){
                // for testing: create a testvalue
                // $aReplacementsForeman[$tTplFile]['replace']['testentry']='dummy value';
                foreach ($aReplacementsForeman[$tTplFile]['replace'] as $sField=>$sValue){
                    if (array_search($sField, $aFields)===false){
                        $aTable['body'][]=array(
                            $oHtml->getIcon('replace') . 
                            $oHtml->getBox('error', sprintf(t('foreman-error-replacement-unknown'), $sField)),
                            $sValue
                        );
                        $aWarnings[]=$tTplFile.': '. sprintf(t('foreman-error-replacement-unknown'), $sField);
                    }
                }
            }

            // --- filecontent of template
            $ContentFile='<br>'.$sFile.'<br><br>'
                    .'<pre style="max-height:35em;">'
                    . preg_replace('/(@replace\[.*\])/U', '<span class="replace">${1}</span>' , htmlentities(file_get_contents($sFile)))
                    .'</pre>';

            // --- output with tabs for a template file
            $sOutReplace.=$oHtml->getNav(
                array(
                    'options'=>array('type'=>'tabs'),
                    'tabs'=>array(
                        $oHtml->getIcon('list') . t('replacement-fields') => '<br>'.$oHtml->getTable($aTable),
                        $oHtml->getIcon('templatefile') . $tTplFile => $ContentFile,
                    )                    
                )
            )
            .'<br></div>';
        }
    } else {
        $sOutReplace.=t('none');
    }
    
    
    // --- reverse check - do templates in foreman physically exist?
    // for testing: create a testfile
    // $aReplacementsForeman['dummytemplate.erb']=array();
    if($aReplacementsForeman){
        foreach(array_keys($aReplacementsForeman) as $sForemanTemplate){
            
            $bFound=false;
            foreach (array_keys($aReplacements) as $sFile) {
                if (basename($sFile)===$sForemanTemplate){
                    $bFound=true;
                    continue;
                }
            }
            if (!$bFound){
                $aWarnings[]=sprintf(t('foreman-error-missing-template'), $sForemanTemplate);
                $sDivIdFile='div4file-'.md5($sForemanTemplate);

                $sOutReplace.='<h4>' . 
                        $oHtml->getLink(array(
                            'onclick'=>'$(\'#'.$sDivIdFile.'\').slideToggle(); $(this).toggleClass(\'closed\'); return false;',
                            'class'=>'expandable closed',
                            'icon'=>'fa-warning',
                            'label'=>$sForemanTemplate,
                        )) . '</h4>'
                        . '<div id="'.$sDivIdFile.'" class="divfileinfos" style="display: none;">'
                        .$oHtml->getBox('error', sprintf(t('foreman-error-missing-template'), $sForemanTemplate))
                        . '</div>'
                        ;

            }
        }
    }

    if (count($aWarnings)){
        $sOut.=$oHtml->getBox('warning', '<ul><li>'.implode('<li>', $aWarnings).'</ul>');
    }
    $sOut.=$sOutReplace;
    
    // ----------------------------------------------------------------------
    // versions
    // ----------------------------------------------------------------------
    $sOut.='
    <h3>' . $oHtml->getIcon('version').t("versions") . '</h3>
    <table>
     <thead>
         <tr>
             <th class="' . $sPhase . '" colspan="3">' . $sPhase . '</th>
         </tr>
     </thead>
     <tbody>
        <tr>' . $oPrj->renderPlacesAsTd($sPhase) . '</tr>
        <tr>
         ' . $oPrj->renderAllPhaseDetails($sPhase, true) . '
        </tr>
     </tbody>
    </table>
    ';
    
    // ----------------------------------------------------------------------
    // list of phases
    // ----------------------------------------------------------------------
    
    // show all  phases if there are more than one
    $sOut.=(count($oPrj->getActivePhases())>1
        ? '<h3>' . $oHtml->getIcon('phase').t("phases") . '</h3>' .  $oPrj->renderPhaseInfo()
        : ''
    )
    ;
    /*
      if ($sFirst == $sPhase) {
      $sOut.='<br><h3>weitere Aktionen</h3>' . $oPrj->renderLink("build");
      }
     * 
     */
} else {
    $sOut.=$oHtml->getBox("error", t("error-no-phase"));
}

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

// -- Ausgabe
echo $sOut;
