<?php


function open_socket()
{
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    if (!($sock === false)) {
        if (socket_connect($sock, "localhost", 6554)) {
            socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 15, 'usec' => 0));
        } else {
            socket_close($sock);
        }
    }
    return $sock;
}


/**
 * @param string $command to send to the server.
 * @return string with the complete reply from the
 *         server. This can be a multiline reply.
 */
function send_cmd($command)
{
    $sock = open_socket();
    if ($sock == false) {
        return "";
    }
    socket_write($sock, $command . "\r\n", 4096);

    $answer = "";
    while (1) {
        $line = socket_read($sock, 4096);
        if ($line === '')
            break;
        $answer .= $line;
    }
    socket_close($sock);

    return $answer;
}


function startsWith($haystack, $needle)
{
    return !strncmp($haystack, $needle, strlen($needle));
}

$response = array(
   'error' => false,
   'msg' => 'Ok',
);


if (isset($_POST['update'])) {

    /* Changing ports does not yet work in the web scripts, disabled. */
    $cmd  = "GLOBAL PUT\r\n";
    $cmd .= "NAME," . $_POST['name'] . "\r\n";
//  $cmd .= "PORT," . $_POST['port'] . "\r\n";
    $cmd .= "TEMP_UUID," . $_POST['temp_uuid'] . "\r\n";
    $cmd .= "HUM_UUID," . $_POST['hum_uuid'] . "\r\n";
    $cmd .= "TEMP_HUM_IDX," . $_POST['temp_hum_idx'] . "\r\n";
    $cmd .= "LCD_ADDRESS," . $_POST['lcd_address'] . "\r\n";
    $cmd .= "LCD_COLS," . $_POST['lcd_cols'] . "\r\n";
    $cmd .= "LCD_ROWS," . $_POST['lcd_rows'] . "\r\n";
    $cmd .= "MQTT_HOST," . $_POST['mqtt_host'] . "\r\n";
    $cmd .= "MQTT_PORT," . $_POST['mqtt_port'] . "\r\n";
    $cmd .= "MQTT_USER," . $_POST['mqtt_user'] . "\r\n";
    $cmd .= "MQTT_PASS," . $_POST['mqtt_pass'] . "\r\n";
//  $cmd .= "WEBSOCKET_PORT," . $_POST['websocket_port'] . "\r\n";
    $cmd .= ".";
    $answer = send_cmd($cmd);
    $arr = explode("\r\n", $answer);
    if (! startsWith($arr[0], "219")) {
	$response['error'] = true;
    }
    exit(json_encode($response));

} else {

    $answer = send_cmd("GLOBAL JSON");
    header("Content-type: application/json");

    $arr = explode("\r\n", $answer);
    if (startsWith($arr[0], "213")) {
    	echo $arr[1];
    } else {
    	echo '{}';
    }
}


?>
