/* gcc -g -O0 `pkg-config --cflags --libs gio-2.0` glib-networking-tls.c */

#include <stdio.h>
#include <string.h>
#include <gio/gio.h>

int
main(void)
{
    GError *error = NULL;

    // raw socket connection to server
    GSocketConnectable *connectable = g_network_address_new ("10.111.112.101", 8443);
    g_assert (connectable);
    GSocketClient *client = g_socket_client_new ();
    GIOStream *con = G_IO_STREAM (g_socket_client_connect (client, connectable, NULL, &error));
    g_assert_no_error (error);
    g_object_unref (client);

    // TLS connection on con
    GIOStream *tls_con = g_tls_client_connection_new (con, connectable, &error);
    g_assert_no_error (error);
    g_object_unref (con);

    //GTlsCertificate *cert = g_tls_certificate_new_from_file ("/tmp/cert-and-key.pem", &error);
    GTlsCertificate *cert = g_tls_certificate_new_from_file ("/tmp/cert.pem", &error);
    g_assert_no_error (error);
    g_tls_connection_set_certificate (G_TLS_CONNECTION (tls_con), cert);

    GTlsDatabase *database = g_tls_file_database_new ("/tmp/ca.pem", &error);
    g_assert_no_error (error);
    g_tls_connection_set_database (G_TLS_CONNECTION (tls_con), database);

    g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tls_con), G_TLS_CERTIFICATE_VALIDATE_ALL);

    g_message ("successfully connected");

    // send request
    const char* request = "GET /api HTTP/1.0\n\n";
    gssize ret = g_output_stream_write (g_io_stream_get_output_stream (tls_con), request, strlen (request), NULL, &error);
    g_assert_no_error (error);
    g_assert_cmpint (ret, ==, strlen (request));

    // read all data
    GDataInputStream *stream = g_data_input_stream_new (g_io_stream_get_input_stream (tls_con));
    char *line;
    while ((line = g_data_input_stream_read_line (stream, NULL, NULL, &error)) != NULL)
        puts(line);
    g_assert_no_error (error);

    return 0;
}
