<?php

require_once('classes/appmonitor-client.class.php');
require_once(__DIR__.'/../deployment/classes/project.class.php');
$oMonitor = new appmonitor();
    
$oMonitor->addCheck(
        array(
            "name" => "simple",
            "description" => "Very simple test",
            "check" => array(
                "function" => "Simple",
                "params" => array(
                    "result" => 0,
                    "value" => "The appmonitor client is reachable.",
                ),
            ),
        )
);

$sCfgfile='../../config/inc_projects_config.php';


// ----------------------------------------------------------------------
// config file
// ----------------------------------------------------------------------

$oMonitor->addCheck(
    array(
        "name" => "read Cfg file",
        "description" => "Check if config file is readable",
        "check" => array(
            "function" => "File",
            "params" => array(
                "filename" => $sCfgfile,
                "file"     => true,
                "readable" => true,
            ),
        ),
    )
);

require_once $sCfgfile;

// echo '<pre>' . print_r($aConfig, 1) . '</pre>';die();

// ----------------------------------------------------------------------
// directories
// ----------------------------------------------------------------------

foreach (array(
    
    'tmpDir'=>array('dir'=>$aConfig['tmpDir'], 'descr'=>'Temp Dir mit git Daten'),
    'configDir'=>array('dir'=>$aConfig['configDir'], 'descr'=>'Ablage der Programm-Config'),
    'dataDir'=>array('dir'=>$aConfig['dataDir'], 'descr'=>'Basisverzeichnis fue DB, Projekt-Configs, SSH-Keys'),
        'dataDir/database'=>array('dir'=>$aConfig['dataDir'].'/database', 'descr'=>'DB-Ablage (Sqlite)'),
        'dataDir/projects'=>array('dir'=>$aConfig['dataDir'].'/projects', 'descr'=>'Projekt-Configdateien'),
        'dataDir/sshkeys'=>array('dir'=>$aConfig['dataDir'].'/sshkeys', 'descr'=>'SSH Keys'),
    
    'buildDir'=>array('dir'=>$aConfig['buildDir'], 'descr'=>'Basisverzeichnis fuer Builds'),
    'packageDir'=>array('dir'=>$aConfig['packageDir'], 'descr'=>'Basisverzeichnis der Pakete und Versionen'),
    'archiveDir'=>array('dir'=>$aConfig['archiveDir'], 'descr'=>'Ablage der gebuildeten Archive'),
    
) as $sKey=>$aItem) {
    $oMonitor->addCheck(
        array(
            "name" => "dir $sKey",
            "description" => $aItem['descr'],
            "check" => array(
                "function" => "File",
                "params" => array(
                    "filename" => $aItem['dir'],
                    "dir"      => true,
                    "writable" => true,
                ),
            ),
        )
    );
}
$oMonitor->addCheck(
	array(
		"name" => "Free space in Archive dir ",
		"description" => "The file storage must have some space left",
		"check" => array(
			"function" => "Diskfree",
			"params" => array(
				"directory" => $aConfig['archiveDir'],
				"warning"   => "2GB",
				"critical"  => "500MB",
			),
		),
	)
);
// ----------------------------------------------------------------------
// count of Projects
// ----------------------------------------------------------------------
$oPrj=new project();
$iProjectCount=count($oPrj->getProjects());
$iInProgress=0;
$iInQueue=0;
foreach ($oPrj->getProjects() as $sPrj) {
        $oPrj2=new project($sPrj);
        $aProgress=$oPrj2->getProgress();
        /*
         * so ist irgendwas anders ... er initialisiert das Projekt nicht
         * 
        $oPrj->setProjectById($sPrj);
        $aProgress=$oPrj->getProgress();
         */
        $iInProgress+=$aProgress['inprogress'] ? 1 : 0;
        $iInQueue+=$aProgress['hasQueue'] ? 1 : 0;
}
$oMonitor->addCheck(
    array(
        "name" => "ci projects",
        "description" => "Count of Projects in CI Webgui",
        "group" => "monitor",
        "check" => array(
            "function" => "Simple",
            "params" => array(
                "result" => $iProjectCount ? RESULT_OK : RESULT_ERROR,
                "value" => "found projects: $iProjectCount",
                "count" => $iProjectCount,
                "visual" => "simple",
            ),
        ),
    )
);
$oMonitor->addCheck(
    array(
        "name" => "ci inProgress",
        "description" => "Projects in progress",
        "group" => "monitor",
        "check" => array(
            "function" => "Simple",
            "params" => array(
                "result" => RESULT_OK,
                "value" => "found projects: $iInProgress",
                "count" => $iInProgress,
                "visual" => "simple",
            ),
        ),
    )
);
$oMonitor->addCheck(
    array(
        "name" => "ci hasqueue",
        "description" => "Waiting for install",
        "group" => "monitor",
        "check" => array(
            "function" => "Simple",
            "params" => array(
                "result" => RESULT_OK,
                "value" => "found projects: $iInQueue",
                "count" => $iInQueue,
                "visual" => "simple",
            ),
        ),
    )
);

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']){
    $oMonitor->addCheck(
        array(
            "name" => "Certificate check",
            "description" => "Check if SSL cert is valid and does not expire soon",
            "check" => array(
                "function" => "Cert",
            ),
        )
    );
}


// ----------------------------------------------------------------------
// foreman
// ----------------------------------------------------------------------

if(isset($aConfig['foreman']['api'])){
    
    require_once(__DIR__.'/../deployment/classes/foremanapi.class.php');
    $oForeman = new ForemanApi($aConfig['foreman']);

    foreach (array('hostgroups', 'hosts') as $sForemanKey){
        $aFData=$oForeman->read(array(
            'request' => array(
                array($sForemanKey),
            ),
            'response' => array(
                'id', 'title'
            ),
        ));
        
        $oMonitor->addCheck(
            array(
                "name" => "Foreman $sForemanKey",
                "description" => "Count of Foreman $sForemanKey",
                "group" => "monitor",
                "check" => array(
                    "function" => "Simple",
                    "params" => array(
                        "result" => count($aFData) ? RESULT_OK : RESULT_ERROR,
                        "value" => "Count of found Foreman $sForemanKey: " . count($aFData)."; response status: ".$oForeman->getResponseStatus() . "; Http-Code ".$oForeman->getResponseInfo('http_code'),
                        "count" => count($aFData),
                        "visual" => "simple",
                    ),
                ),
            )
        );
    }
}

// ----------------------------------------------------------------------
// ssh targets
// ----------------------------------------------------------------------

if(count($aConfig['mirrorPackages'])){
    foreach($aConfig['mirrorPackages'] as $sHostKey=>$aData){
        /*
        [puppet.one] => Array
        (
            [type] => rsync
            [runas] => 
            [target] => copy-deployment@puppet:/var/shared/imldeployment
        )
         */
        $sTargetHost = preg_replace('/\:.*/', '', $aData['target']);
        $sCmd='ssh '.$sTargetHost. ' ls -1';

        exec($sCmd, $sOut, $iRc);
        $oMonitor->addCheck(
            array(
                "name" => "mirror target $sHostKey",
                "description" => "Sync target of generated packages",
                "group" => "network",
                "check" => array(
                    "function" => "Simple",
                    "params" => array(
                        "result" => $iRc ? RESULT_ERROR : RESULT_OK,
                        "value" => "Command [$sCmd] returns with exitcode $iRc; output: ".implode(" ", $sOut),
                    ),
                ),
            )
        );
    }
    
}
foreach(array(
    /*
    array(
        'host'=>'gitlab.iml.unibe.ch',
        'port'=>22,
        'descr'=>'SSH port to Gitlab on gitlab.iml.unibe.ch'
    ),
     */
    array(
        'host'=>'git-repo.iml.unibe.ch',
        'port'=>22,
        'descr'=>'SSH port to Gitlab on git-repo.iml.unibe.ch'
    ),
    array(
        'host'=>'github.com',
        'port'=>22,
        'descr'=>'SSH port to Github'
    ),
) as $aDescr){
    $oMonitor->addCheck(
            array(
                    "name" => 'port check '.$aDescr['host'].':'.$aDescr['port'],
                    "description" => $aDescr['descr'],
                    "group" => "cloud",
                    "check" => array(
                            "function" => "PortTcp",
                            "params" => array(
                                    "port"=>$aDescr['port'],
                                    "host"=>$aDescr['host'],
                            ),
                    ),
            )
    );
}


// ----------------------------------------------------------------------
// database
// ----------------------------------------------------------------------

$sSqlitefile=$aConfig['dataDir'].'/database/logs.db';
$oMonitor->addCheck(
    array(
        "name" => "Sqlite DB for action logs",
        "description" => "Connect sqlite db ". basename($sSqlitefile),
        "check" => array(
            "function" => "SqliteConnect",
            "params" => array(
                "db"=>$sSqlitefile
            ),
        ),
    )
);

// ----------------------------------------------------------------------
// system stuff
// ----------------------------------------------------------------------
$oMonitor->addCheck(
    array(
        "name" => "plugin Load",
        "description" => "current load",
        "check" => array(
            "function" => "Loadmeter",
            "params" => array(
                "warning" => 1.0,
                "error" => 3,
            ),
        ),
        "worstresult" => RESULT_OK
    )
);
$oMonitor->addCheck(
    array(
        "name" => "plugin ApacheProcesses",
        "description" => "Apache processes",
        "check" => array(
            "function" => "ApacheProcesses",
            "params" => array(
                "warning" => 50,
                "error" => 75,
            ),
        ),
        "worstresult" => RESULT_OK
    )
);


// Gesamt-Ergebnis - ohne Param=aut. max. Wert nehmen
$oMonitor->setResult();

// Ausgabe
$oMonitor->render();