<?php
//Cron automático, con llamada manual por argumentos

require_once __DIR__ .'/../functions.php';
$db_conn = dbconn();

if (isset($argv[1]) && (int)$argv[1] != 0){ //Si se envió un servidor forzado por un argumento...
    $ID_SERV = (int)$argv[1];

    $pcsenabled = dbw_query($db_conn,"SELECT * FROM SERVERS WHERE ID_SERV='$ID_SERV'");
}else if (isset($RETRIEVE_DATA)){
    $ID_SERV = (int)$RETRIEVE_DATA;
    $pcsenabled = dbw_query($db_conn,"SELECT * FROM SERVERS WHERE ID_SERV='$ID_SERV'");
}else{
    $pcsenabled = dbw_query($db_conn,"SELECT * FROM SERVERS WHERE `Enabled`=1");
}

require_once __DIR__ .'/servers.php';

$tryping = ping('127.0.0.1'); //Try if ping work

while ($pc = dbw_fetch_array($db_conn,$pcsenabled)){
    $ID_SERV = $pc['ID_SERV'];

    foreach ($pc as $key => $value){ //Clean data, and update data in db if it's bad
        if ($pc[$key] != trim($pc[$key])){
            $pc[$key] = trim($pc[$key]);
            dbw_query($db_conn,"UPDATE SERVERS SET `$key`='$pc[$key]' WHERE ID_SERV='$ID_SERV'");
        }
    }
	
	/* Some hosts doesn't have an IP, has a DNS, then first check if host is a real IP, or can be DNS queried. Ever work with the IP */
	if (!filter_var($pc['IP'], FILTER_VALIDATE_IP)){ //If its not a IP (Its a hostname)
		$pc['IP'] = gethostbyname($pc['IP'].'.'); //Resolve hostname and set IP
		if (!filter_var($pc['IP'], FILTER_VALIDATE_IP)){ //If domain doesn't resolve, it returns a string or false, will not validate
			$notdetectedip = 1; // Return 1 if IP can't be translated (Computer off or bad writed)
		}
	}
	


    $time = time();
	$pc['Password'] = decodePassword($pc['Password'],$pc['IV']); //Decoding password before starting
    
    if ($tryping != -1){ //Only if I can ping. (Root/cron)
        $res = cron_ping($db_conn,$time,$pc);
		if ($res == -1 ){ //PC Off
			continue;
		}
    }
	
	/* Update SQL Last Check time */
	$timestamp = time();
	dbw_query($db_conn,"UPDATE SERVERS SET LastCheck='$timestamp' WHERE ID_SERV='$ID_SERV'");

    //This tries to login computer, and if not, cancel going next things.
    $result = try_login($pc);
    if ($result == 1){
        dbw_query($db_conn,"UPDATE SERVERS SET BadCreds='0' WHERE ID_SERV='$ID_SERV'");
    }else if ($result == 2){ //Windows WMI error, not about credentials
        dbw_query($db_conn,"UPDATE SERVERS SET BadCreds='2' WHERE ID_SERV='$ID_SERV'");
        continue;
    }else{
        dbw_query($db_conn,"UPDATE SERVERS SET BadCreds='1' WHERE ID_SERV='$ID_SERV'");
        continue;
    }

    $tstamp = dbw_query_fetch_array($db_conn,"SELECT `Timestamp` FROM S_HDDSTAT WHERE ID_SERV='$pc[ID_SERV]' ORDER BY `Timestamp` DESC LIMIT 1")[0];
    if ((!$tstamp || abs(time() - $tstamp) > (30*60)) || isset($argv[1])){ //30 minutos o forzar si lo piden
        cron_status($db_conn,$time,$pc);
    }
    
    //Get type of linux
    if ($pc['SO'] == 'LINUX'){ //Only update if needs (Todo? Well, as is only checks if no SYSTEMD or SERVICE found)
        detect_linux($pc);
    }

    //Services
    $services = dbw_query($db_conn,"SELECT ID_SERV,`Name` FROM S_SERVICES WHERE ID_SERV='$pc[ID_SERV]' AND `Enabled`=1 AND `Type`='SERVICE'");
    while ($service = dbw_fetch_array($db_conn,$services)){
        cron_service($db_conn,$time,$pc,$service);
    }

    //Web pages
    $services = dbw_query($db_conn,"SELECT ID_SERV,`Name` FROM S_SERVICES WHERE ID_SERV='$pc[ID_SERV]' AND `Enabled`=1 AND `Type`='WEBSERVICE'");
    while ($service = dbw_fetch_array($db_conn,$services)){
        cron_webservice($db_conn,$time,$pc,$service);
    }

    cron_uptime($db_conn,$time,$pc); //Uptime


    cron_getversion($db_conn,$pc); //Windows/Linux version name

}


//Cleaning
$when = time() - (getsysopt('AUTODELETE') * 24*3600);
dbw_query($db_conn,"DELETE FROM S_HDDSTAT WHERE `Timestamp` < '$when'");
dbw_query($db_conn,"DELETE FROM S_HISTRAM WHERE `Timestamp` < '$when'");
dbw_query(dbconn(),"DELETE FROM S_HISTPING WHERE `Timestamp` < '$when'");
dbw_query(dbconn(),"DELETE FROM S_HISTSERVICES WHERE `Timestamp` < '$when'");