<?php

function machine_add_to_monitoring($con, $conf, $machine, $ignore_dot_ini_activation='no'){
    $json["status"] = "success";
    $json["message"] = "Successfuly queried API.";

    if($ignore_dot_ini_activation == 'yes' || $conf["monitoring_plugin"]["call_monitoring_plugin"]){
        $q = "SELECT INET_NTOA( ips.ip ) AS ipaddr FROM ips,machines,networks WHERE machines.id='".$machine["id"]."' "
                ."AND ips.machine=machines.id AND ips.network=networks.id AND networks.role!='ipmi' "
                ."AND networks.role!='vm-net' AND networks.role!='vip' AND networks.is_public='no' AND networks.role!='ceph-cluster'";
        $r = mysqli_query($con, $q);
        if($r === FALSE){
            $json["status"] = "error";
            $json["message"] = mysqli_error($con). " doing $q";
            return $json;
        }
        $n = mysqli_num_rows($r);

        if($n == 1){
            $ip = mysqli_fetch_array($r);
            $ipaddr = $ip["ipaddr"];

            $q = "SELECT * FROM ifnames WHERE switchport_name!='unknown' AND switch_hostname!='unknown' AND machine_id='".$machine["id"]."' LIMIT 1";
            $r = mysqli_query($con, $q);
            if($r === FALSE){
                $json["status"] = "error";
                $json["message"] = mysqli_error($con). " doing $q";
                return $json;
            }
            $n = mysqli_num_rows($r);
            if($n > 0){
                $if = mysqli_fetch_array($r);

                $switch_hostname = $if["switch_hostname"];

                $script_path = $conf["monitoring_plugin"]["monitoring_create_script_path"];
                if( file_exists($script_path) && is_executable($script_path) ){
                    $cmd = "$script_path --hostname ".$machine["hostname"]." --ip-address $ipaddr --switch-hostname $switch_hostname --role ".$machine["role"];
                    $output = array();
                    $return_var = 0;
                    exec($cmd, $output, $return_var);
                    $json["data"]["command"] = $cmd;
                    $json["data"]["output"] = $output;
                }
            }
        }
    }
    return $json;
}

function machine_delete_from_monitoring($con, $conf, $machine){
    $json["status"] = "success";
    $json["message"] = "Successfuly queried API.";

    $script_path = $conf["monitoring_plugin"]["monitoring_delete_script_path"];
    if( file_exists($script_path) && is_executable($script_path) ){
        $cmd = "$script_path --hostname ".$machine["hostname"];
        $output = array();
        $return_var = 0;
        exec($cmd, $output, $return_var);
        $json["data"]["command"] = $cmd;
        $json["data"]["output"] = $output;
    }
    return $json;
}

?>