#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <glib.h>
#include <libnotify/notify.h>
#include <stdlib.h>

#include "update-notifier.h"

#define STATUS_PATH "/var/snap/canonical-livepatch/current/status"

static void
init_notification ()
{
    notify_init ("update-notifier");
}

static void
init_gettext ()
{
    setlocale (LC_ALL, "");
    bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
    bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
    textdomain (GETTEXT_PACKAGE);
}

static void
show_notification (const char *summary, const char *body, const char *icon)
{
    NotifyNotification *n = notify_notification_new (summary, body, icon);
    notify_notification_set_timeout (n, 60000);
    notify_notification_show (n, NULL);
    g_object_unref (n);
}

static void
get_event_from_file (const char* filename, char **event, char **description)
{
    g_autofree gchar *content = NULL;

    g_return_if_fail (filename != NULL);
    g_return_if_fail (event != NULL);
    g_return_if_fail (description != NULL);

    *event = *description = NULL;

    g_file_get_contents (filename, &content, NULL, NULL);

    if (content) {
        gchar **strings = g_strsplit (content, " ", 2);

        if (g_strv_length (strings) > 0)
            *event = g_strdup (g_strstrip (strings[0]));
        if (g_strv_length (strings) > 1)
            *description = g_strdup (g_strstrip (strings[1]));

        g_strfreev (strings);
    }
}

static void
show_status_notification ()
{
    if (g_file_test (STATUS_PATH, G_FILE_TEST_EXISTS))
    {
        g_autofree gchar *event, *description;
        get_event_from_file (STATUS_PATH, &event, &description);

        if (!g_strcmp0 (event, "applied")) {
            g_autofree gchar *body = NULL;

            int num_updates = atoi(description);
            body = g_strdup_printf(
                ngettext("%d Livepatch update has been successfully applied.",
                         "%d Livepatch updates have been successfully applied.",
                         num_updates),
                num_updates);

            show_notification (_("Canonical Livepatch"), body, NULL);
        }
    }
}

int
main (int argc, char **argv)
{
    init_notification ();
    init_gettext ();

    show_status_notification ();

    return EXIT_SUCCESS;
}
