<?php

require_once("read_conf.php");
require_once("db.php");

$conf = readmyconf();
$con = connectme($conf);


$data = json_decode(file_get_contents('php://input'), true);

$remote_addr = $_SERVER['REMOTE_ADDR'];

$memory_size = $data["memory"][0]["size"];
$memory_type = $data["memory"][0]["type"];
$memory_speed = $data["memory"][0]["speed"];
$memory_manufacturer = $data["memory"][0]["manufacturer"];

$serial_number = $data["machine"][0]["serial"];

$r = mysqli_query($con, "SELECT * FROM machines WHERE ipaddr='" . $remote_addr . "'");
$n = mysqli_num_rows($r);
if($n == 0){
    $r = mysqli_query($con, "INSERT INTO machines (ipaddr, serial, memory) VALUES ('" . $remote_addr. "', '$serial_number' , '".$memory_size."')");
    $id = mysqli_insert_id($con);

    foreach($data["blockdevices"] as &$blockdevice){
        $blk_name = $blockdevice['name'];
        $blk_size = $blockdevice['size'];
        $r = mysqli_query($con, "INSERT INTO blockdevices (id, machine_id, name, size_mb) VALUES ('', '".$id."', '".$blk_name."', '".$blk_size."')");
    }

    foreach($data["interfaces"] as &$iface){
        $if_name = $iface["name"];
        $if_macaddr = $iface["macaddr"];
        $r = mysqli_query($con, "INSERT INTO ifnames (id, machine_id, name, macaddr) VALUES ('', '".$id."', '".$if_name."', '".$if_macaddr."')");
    }
}else{
    $a = mysqli_fetch_array($r);
    $id = $a["id"];
    // We keep the machine id...
    $req = "UPDATE machines SET memory='".$memory_size."', serial='$serial_number', lastseen=NOW() WHERE ipaddr='" . $remote_addr. "'";
    $r = mysqli_query($con, $req);
    // ...but we delete and recreate blockdevices and ifnames on each report
    $r = mysqli_query($con, "DELETE FROM blockdevices WHERE machine_id='".$id."'");
    $r = mysqli_query($con, "DELETE FROM ifnames WHERE machine_id='".$id."'");
    foreach($data["blockdevices"] as &$blockdevice){
        $blk_name = $blockdevice['name'];
        $blk_size = $blockdevice['size'];
        $r = mysqli_query($con, "INSERT INTO blockdevices (id, machine_id, name, size_mb) VALUES ('', '".$id."', '".$blk_name."', '".$blk_size."')");
    }

    foreach($data["interfaces"] as &$iface){
        $if_name = $iface["name"];
        $if_macaddr = $iface["macaddr"];
        $r = mysqli_query($con, "INSERT INTO ifnames (id, machine_id, name, macaddr) VALUES ('', '".$id."', '".$if_name."', '".$if_macaddr."')");
    }
}

print("Ok\n");
?>
