/*

  Copyright (c) 2010-2011 Samuel Lidén Borell <samuel@kodafritt.se>
  Copyright (c) 2015 <the.cypher@gmail.com>
  Copyright (c) 2019-2020 <bakasura@protonmail.ch>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#include "config.h"

#include <glib.h>
#include <gtk/gtk.h>
#include <stdlib.h>
#include <string.h>
#include "zoitechat-plugin.h"

#include "fish.h"
#include "dh1080.h"
#include "keystore.h"
#include "irc.h"

static const char *fish_modes[] = {"", "ECB", "CBC", NULL};

static const char plugin_name[] = "FiSHLiM";
static const char plugin_desc[] = "Encryption plugin for the FiSH protocol. Less is More!";
static const char plugin_version[] = "1.0.0";

static const char usage_setkey[] = "Usage: SETKEY [<nick or #channel>] [<mode>:]<password>, sets the key for a channel or nick. Modes: ECB, CBC";
static const char usage_delkey[] = "Usage: DELKEY [<nick or #channel>], deletes the key for a channel or nick";
static const char usage_keyx[] = "Usage: KEYX [<nick>] [ECB|CBC], performs DH1080 key-exchange with <nick>";
static const char usage_topic[] = "Usage: TOPIC+ <topic>, sets a new encrypted topic for the current channel";
static const char usage_notice[] = "Usage: NOTICE+ <nick or #channel> <notice>";
static const char usage_msg[] = "Usage: MSG+ <nick or #channel> <message>";


static zoitechat_plugin *ph;
static GHashTable *pending_exchanges;
static GtkWidget *fishlim_dialog;
static GtkWidget *fishlim_target_entry;
static GtkWidget *fishlim_key_entry;
static GtkWidget *fishlim_mode_combo;
static GtkWidget *fishlim_status_label;
static GtkListStore *fishlim_store;
static GtkWidget *fishlim_view;


/**
 * Compare two nicks using the current plugin
 */
int irc_nick_cmp(const char *a, const char *b) {
    return zoitechat_nickcmp (ph, a, b);
}

/**
 * Returns the path to the key store file.
 */
gchar *get_config_filename(void) {
    char *filename_fs, *filename_utf8;

    filename_utf8 = g_build_filename(zoitechat_get_info(ph, "configdir"), "addon_fishlim.conf", NULL);
    filename_fs = g_filename_from_utf8 (filename_utf8, -1, NULL, NULL, NULL);

    g_free (filename_utf8);
    return filename_fs;
}

static inline gboolean irc_is_query (const char *name) {
    const char *chantypes = zoitechat_list_str (ph, NULL, "chantypes");

    return strchr (chantypes, name[0]) == NULL;
}

static zoitechat_context *find_context_on_network (const char *name) {
    zoitechat_list *channels;
    zoitechat_context *ret = NULL;
    int id;

    if (zoitechat_get_prefs(ph, "id", NULL, &id) != 2)
        return NULL;

    channels = zoitechat_list_get(ph, "channels");
    if (!channels)
        return NULL;

    while (zoitechat_list_next(ph, channels)) {
        int chan_id = zoitechat_list_int(ph, channels, "id");
        const char *chan_name = zoitechat_list_str(ph, channels, "channel");

        if (chan_id == id && chan_name && irc_nick_cmp (chan_name, name) == 0) {
            ret = (zoitechat_context*)zoitechat_list_str(ph, channels, "context");
            break;
        }
    };

    zoitechat_list_free(ph, channels);
    return ret;
}

/**
 * Retrive the field for own user in current context
 * @return the field value
 */
char *get_my_info(const char *field, gboolean find_in_other_context) {
    char *result = NULL;
    const char *own_nick;
    zoitechat_list *list;
    zoitechat_context *ctx_current, *ctx_channel;

    /* Display message */
    own_nick = zoitechat_get_info(ph, "nick");

    if (!own_nick)
        return NULL;

    /* Get field for own nick if any */
    list = zoitechat_list_get(ph, "users");
    if (list) {
        while (zoitechat_list_next(ph, list)) {
            if (irc_nick_cmp(own_nick, zoitechat_list_str(ph, list, "nick")) == 0)
                result = g_strdup(zoitechat_list_str(ph, list, field));
        }
        zoitechat_list_free(ph, list);
    }

    if (result) {
        return result;
    }

    /* Try to get from a channel (we are outside a channel)  */
    if (!find_in_other_context) {
        return NULL;
    }

    list = zoitechat_list_get(ph, "channels");
    if (list) {
        ctx_current = zoitechat_get_context(ph);
        while (zoitechat_list_next(ph, list)) {
            ctx_channel = (zoitechat_context *) zoitechat_list_str(ph, list, "context");

            zoitechat_set_context(ph, ctx_channel);
            result = get_my_info(field, FALSE);
            zoitechat_set_context(ph, ctx_current);

            if (result) {
                break;
            }
        }
        zoitechat_list_free(ph, list);
    }

    return result;
}

/**
 * Retrive the prefix character for own nick in current context
 * @return @ or + or NULL
 */
char *get_my_own_prefix(void) {
    return get_my_info("prefix", FALSE);
}

/**
 * Retrive the mask for own nick in current context
 * @return Host name in the form: user@host (or NULL if not known)
 */
char *get_my_own_host(void) {
    return get_my_info("host", TRUE);
}

/**
 * Calculate the length of prefix for current user in current context
 *
 * @return Length of prefix
 */
int get_prefix_length(void) {
    char *own_host;
    int prefix_len = 0;

    /* ':! ' + 'nick' + 'ident@host', e.g. ':user!~name@mynet.com ' */
    prefix_len = 3 + strlen(zoitechat_get_info(ph, "nick"));
    own_host = get_my_own_host();
    if (own_host) {
        prefix_len += strlen(own_host);
    } else {
        /* https://stackoverflow.com/questions/8724954/what-is-the-maximum-number-of-characters-for-a-host-name-in-unix */
        prefix_len += 64;
    }
    g_free(own_host);

    return prefix_len;
}

/**
 * Try to decrypt the first occurrence of fish message
 * 
 * @param message  Message to decrypt
 * @param key     Key of message
 * @return Array of char with decrypted message or NULL. The returned string 
 * should be freed with g_free() when no longer needed.
 */
char *decrypt_raw_message(const char *message, const char *key) {
    const char *prefixes[] = {"+OK ", "mcps ", NULL};
    char *start = NULL, *end = NULL;
    char *left = NULL, *right = NULL;
    char *encrypted = NULL, *decrypted = NULL;
    int length = 0;
    int index_prefix;
    enum fish_mode mode;
    GString *message_decrypted;
    char *result = NULL;

    if (message == NULL || key == NULL)
        return NULL;

    for (index_prefix = 0; index_prefix < 2; index_prefix++) {
        start = g_strstr_len(message, strlen(message), prefixes[index_prefix]);
        if (start) {
            /* Length ALWAYS will be less that original message
             * add '[CBC] ' length */
            message_decrypted = g_string_sized_new(strlen(message) + 6);

            /* Left part of message */
            left = g_strndup(message, start - message);
            g_string_append(message_decrypted, left);
            g_free(left);

            /* Encrypted part */
            start += strlen(prefixes[index_prefix]);
            end = g_strstr_len(start, strlen(message), " ");
            if (end) {
                length = end - start;
                right = end;
            }

            if (length > 0) {
                encrypted = g_strndup(start, length);
            } else {
                encrypted = g_strdup(start);
            }
            decrypted = fish_decrypt_from_nick(key, encrypted, &mode);
            g_free(encrypted);

            if (decrypted == NULL) {
                g_string_free(message_decrypted, TRUE);
                return NULL;
            }

            /* Add encrypted flag */
            g_string_append(message_decrypted, "[");
            g_string_append(message_decrypted, fish_modes[mode]);
            g_string_append(message_decrypted, "] ");
            /* Decrypted message */
            g_string_append(message_decrypted, decrypted);
            g_free(decrypted);

            /* Right part of message */
            if (right) {
                g_string_append(message_decrypted, right);
            }

            result = message_decrypted->str;
            g_string_free(message_decrypted, FALSE);
            return result;
        }
    }

    return NULL;
}

/**
 * Called when a message is to be sent.
 */
static int handle_outgoing(char *word[], char *word_eol[], void *userdata) {
    char *prefix;
    enum fish_mode mode;
    char *message;
    GString *command;
    GSList *encrypted_list, *encrypted_item;

    const char *channel = zoitechat_get_info(ph, "channel");

    /* Check if we can encrypt */
    if (!fish_nick_has_key(channel)) return ZOITECHAT_EAT_NONE;

    command = g_string_new("");
    g_string_printf(command, "PRIVMSG %s :+OK ", channel);

    encrypted_list = fish_encrypt_for_nick(channel, word_eol[1], &mode, get_prefix_length() + command->len);
    if (!encrypted_list) {
        g_string_free(command, TRUE);
        return ZOITECHAT_EAT_NONE;
    }

    /* Get prefix for own nick if any */
    prefix = get_my_own_prefix();

    /* Add encrypted flag */
    message = g_strconcat("[", fish_modes[mode], "] ", word_eol[1], NULL);

    /* Display message */
    zoitechat_emit_print(ph, "Your Message", zoitechat_get_info(ph, "nick"), message, prefix, NULL);
    g_free(message);

    /* Send encrypted messages */
    encrypted_item = encrypted_list;
    while (encrypted_item)
    {
        zoitechat_commandf(ph, "%s%s", command->str, (char *)encrypted_item->data);

        encrypted_item = encrypted_item->next;
    }

    g_free(prefix);
    g_string_free(command, TRUE);
    g_slist_free_full(encrypted_list, g_free);

    return ZOITECHAT_EAT_ZOITECHAT;
}

/**
 * Called when a channel message or private message is received.
 */
static int handle_incoming(char *word[], char *word_eol[], zoitechat_event_attrs *attrs, void *userdata) {
    const char *prefix;
    const char *command;
    const char *recipient;
    const char *raw_message = word_eol[1];
    char *sender_nick;
    char *decrypted;
    size_t parameters_offset;
    GString *message;

    if (!irc_parse_message((const char **)word, &prefix, &command, &parameters_offset))
        return ZOITECHAT_EAT_NONE;

    /* Topic (command 332) has an extra parameter */
    if (!strcmp(command, "332"))
        parameters_offset++;

    /* Extract sender nick and recipient nick/channel and try to decrypt */
    recipient = word[parameters_offset];
    decrypted = decrypt_raw_message(raw_message, recipient);
    if (decrypted == NULL) {
        sender_nick = irc_prefix_get_nick(prefix);
        decrypted = decrypt_raw_message(raw_message, sender_nick);
        g_free(sender_nick);
    }

    /* Nothing to decrypt */
    if (decrypted == NULL)
        return ZOITECHAT_EAT_NONE;

    /* Build decrypted message */

    /* decrypted + 'RECV ' + '@time=YYYY-MM-DDTHH:MM:SS.fffffZ ' */
    message = g_string_sized_new (strlen(decrypted) + 5 + 33);
    g_string_append (message, "RECV ");

    if (attrs->server_time_utc)
    {
        GTimeVal tv = { (glong)attrs->server_time_utc, 0 };
        char *timestamp = g_time_val_to_iso8601 (&tv);

       g_string_append (message, "@time=");
       g_string_append (message, timestamp);
       g_string_append (message, " ");
       g_free (timestamp);
    }

    g_string_append (message, decrypted);
    g_free(decrypted);

    /* Fake server message
     * RECV command will throw this function again, if message have multiple
     * encrypted data, we will decrypt all */
    zoitechat_command(ph, message->str);
    g_string_free (message, TRUE);

    return ZOITECHAT_EAT_ZOITECHAT;
}

static int handle_keyx_notice(char *word[], char *word_eol[], void *userdata) {
    const char *dh_message = word[4];
    const char *dh_pubkey = word[5];
    zoitechat_context *query_ctx;
    const char *prefix;
    char *sender, *secret_key, *priv_key = NULL;
    enum fish_mode mode = FISH_ECB_MODE;

    if (!*dh_message || !*dh_pubkey || strlen(dh_pubkey) != 181)
        return ZOITECHAT_EAT_NONE;

    if (!irc_parse_message((const char**)word, &prefix, NULL, NULL) || !prefix)
        return ZOITECHAT_EAT_NONE;

    sender = irc_prefix_get_nick(prefix);
    query_ctx = find_context_on_network(sender);
    if (query_ctx)
        g_assert(zoitechat_set_context(ph, query_ctx) == 1);

    dh_message++; /* : prefix */

    if (g_strcmp0 (word[6], "CBC") == 0)
        mode = FISH_CBC_MODE;

    if (!strcmp(dh_message, "DH1080_INIT")) {
        char *pub_key;

        zoitechat_printf(ph, "Received public key from %s (%s), sending mine...", sender, fish_modes[mode]);
        if (dh1080_generate_key(&priv_key, &pub_key)) {
            zoitechat_commandf(ph, "quote NOTICE %s :DH1080_FINISH %s%s", sender, pub_key, (mode == FISH_CBC_MODE) ? " CBC" : "");
            g_free(pub_key);
        } else {
            zoitechat_printf(ph, "Failed to generate keys");
            goto cleanup;
        }
    } else if (!strcmp (dh_message, "DH1080_FINISH")) {
        char *sender_lower = g_ascii_strdown(sender, -1);
        /* FIXME: Properly respect irc casing */
        priv_key = g_hash_table_lookup(pending_exchanges, sender_lower);
        g_hash_table_steal(pending_exchanges, sender_lower);
        g_free(sender_lower);

        if (!priv_key) {
            zoitechat_printf(ph, "Received a key exchange response for unknown user: %s", sender);
            goto cleanup;
        }
    } else {
        /* Regular notice */
        g_free(sender);
        return ZOITECHAT_EAT_NONE;
    }

    if (dh1080_compute_key(priv_key, dh_pubkey, &secret_key)) {
        keystore_store_key(sender, secret_key, mode);
        zoitechat_printf(ph, "Stored new key for %s (%s)", sender, fish_modes[mode]);
        g_free(secret_key);
    } else {
        zoitechat_printf(ph, "Failed to create secret key!");
    }

cleanup:
    g_free(sender);
    g_free(priv_key);
    return ZOITECHAT_EAT_ALL;
}


static const char *fishlim_gui_target(void) {
    const char *target;

    target = gtk_entry_get_text(GTK_ENTRY(fishlim_target_entry));
    if (target && *target)
        return target;

    return zoitechat_get_info(ph, "channel");
}

static void fishlim_gui_refresh(void) {
    GtkTreeIter iter;
    gchar **targets;
    gsize length, i;
    const char *target;
    char *key;
    enum fish_mode mode;

    if (!fishlim_dialog)
        return;

    gtk_list_store_clear(fishlim_store);
    targets = keystore_get_targets(&length);

    for (i = 0; targets && i < length; i++) {
        key = keystore_get_key(targets[i], &mode);
        gtk_list_store_append(fishlim_store, &iter);
        gtk_list_store_set(fishlim_store, &iter, 0, targets[i], 1, fish_modes[mode], 2, key ? "Stored" : "Unreadable", -1);
        g_free(key);
    }

    g_strfreev(targets);

    target = fishlim_gui_target();
    key = target ? keystore_get_key(target, &mode) : NULL;

    if (key) {
        char *text = g_strdup_printf("Key stored for %s (%s)", target, fish_modes[mode]);
        gtk_label_set_text(GTK_LABEL(fishlim_status_label), text);
        gtk_combo_box_set_active(GTK_COMBO_BOX(fishlim_mode_combo), mode == FISH_CBC_MODE ? 1 : 0);
        g_free(text);
        g_free(key);
    } else if (target && *target) {
        char *text = g_strdup_printf("No key for %s", target);
        gtk_label_set_text(GTK_LABEL(fishlim_status_label), text);
        g_free(text);
    } else {
        gtk_label_set_text(GTK_LABEL(fishlim_status_label), "No target selected");
    }
}

static void fishlim_gui_refresh_cb(GtkWidget *widget, gpointer data) {
    fishlim_gui_refresh();
}

static void fishlim_gui_send_channel_key(const char *channel, const char *mode, const char *key) {
    GtkWidget *dialog, *content, *entry, *label;
    char **users;
    int i;

    if (!channel || !*channel || irc_is_query(channel))
        return;

    dialog = gtk_dialog_new_with_buttons("Share Channel Key", GTK_WINDOW(fishlim_dialog), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, "_Skip", GTK_RESPONSE_CANCEL, "_Send", GTK_RESPONSE_OK, NULL);
    content = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
    label = gtk_label_new("Send this channel key to users by private message. Enter users separated by commas.");
    gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
    gtk_box_pack_start(GTK_BOX(content), label, FALSE, FALSE, 6);
    entry = gtk_entry_new();
    gtk_entry_set_placeholder_text(GTK_ENTRY(entry), "nick1, nick2, nick3");
    gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE);
    gtk_box_pack_start(GTK_BOX(content), entry, FALSE, FALSE, 6);
    gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK);
    gtk_widget_show_all(dialog);

    if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) {
        users = g_strsplit(gtk_entry_get_text(GTK_ENTRY(entry)), ",", -1);
        for (i = 0; users && users[i]; i++) {
            char *user = g_strstrip(users[i]);
            if (*user)
                zoitechat_commandf(ph, "msg %s Encrypted chat invite: join %s, open FiSHLiM Key Manager, add channel %s with %s key: %s. Key exchange is for private messages only.", user, channel, channel, mode, key);
        }
        g_strfreev(users);
    }

    gtk_widget_destroy(dialog);
}

static void fishlim_gui_set(GtkWidget *widget, gpointer data) {
    const char *target = fishlim_gui_target();
    const char *key = gtk_entry_get_text(GTK_ENTRY(fishlim_key_entry));
    const char *mode = gtk_combo_box_get_active(GTK_COMBO_BOX(fishlim_mode_combo)) == 1 ? "CBC" : "ECB";

    if (!target || !*target || !key || !*key) {
        zoitechat_printf(ph, "%s\n", usage_setkey);
        return;
    }

    zoitechat_commandf(ph, "SETKEY %s %s:%s", target, mode, key);
    fishlim_gui_send_channel_key(target, mode, key);
    gtk_entry_set_text(GTK_ENTRY(fishlim_key_entry), "");
    fishlim_gui_refresh();
}

static gboolean fishlim_gui_confirm_delete(const char *target) {
    GtkWidget *dialog;
    char *message;
    gboolean confirmed;

    message = g_strdup_printf("Delete the key for %s?", target);
    dialog = gtk_message_dialog_new(GTK_WINDOW(fishlim_dialog), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE, "%s", message);
    gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog), "This cannot be undone.");
    gtk_dialog_add_buttons(GTK_DIALOG(dialog), "_Cancel", GTK_RESPONSE_CANCEL, "_Delete", GTK_RESPONSE_ACCEPT, NULL);
    gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CANCEL);
    confirmed = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT;
    gtk_widget_destroy(dialog);
    g_free(message);
    return confirmed;
}

static char *fishlim_gui_selected_target(void) {
    GtkTreeSelection *selection;
    GtkTreeModel *model;
    GtkTreeIter iter;
    char *target = NULL;

    if (!fishlim_view)
        return NULL;

    selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(fishlim_view));
    if (gtk_tree_selection_get_selected(selection, &model, &iter))
        gtk_tree_model_get(model, &iter, 0, &target, -1);

    return target;
}

static void fishlim_gui_delete(GtkWidget *widget, gpointer data) {
    char *selected = fishlim_gui_selected_target();
    const char *target = selected ? selected : fishlim_gui_target();

    if (!target || !*target) {
        zoitechat_printf(ph, "%s\n", usage_delkey);
        g_free(selected);
        return;
    }

    if (fishlim_gui_confirm_delete(target)) {
        zoitechat_commandf(ph, "DELKEY %s", target);
        fishlim_gui_refresh();
    }

    g_free(selected);
}

static char *fishlim_gui_prompt_target(const char *title, const char *initial) {
    GtkWidget *dialog, *content, *entry;
    char *target = NULL;

    dialog = gtk_dialog_new_with_buttons(title, GTK_WINDOW(fishlim_dialog), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, "_Cancel", GTK_RESPONSE_CANCEL, "_OK", GTK_RESPONSE_OK, NULL);
    content = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
    entry = gtk_entry_new();
    if (initial && *initial)
        gtk_entry_set_text(GTK_ENTRY(entry), initial);
    gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE);
    gtk_box_pack_start(GTK_BOX(content), gtk_label_new("Private message user"), FALSE, FALSE, 6);
    gtk_box_pack_start(GTK_BOX(content), entry, FALSE, FALSE, 6);
    gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK);
    gtk_widget_show_all(dialog);

    if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) {
        const char *text = gtk_entry_get_text(GTK_ENTRY(entry));
        if (text && *text)
            target = g_strdup(text);
    }

    gtk_widget_destroy(dialog);
    return target;
}

static void fishlim_gui_keyx(GtkWidget *widget, gpointer data) {
    char *target;
    const char *initial = fishlim_gui_target();
    const char *mode = gtk_combo_box_get_active(GTK_COMBO_BOX(fishlim_mode_combo)) == 1 ? "CBC" : "ECB";

    if (!initial || !*initial || !irc_is_query(initial))
        initial = NULL;

    target = fishlim_gui_prompt_target("Key Exchange", initial);
    if (!target)
        return;

    zoitechat_commandf(ph, "KEYX %s %s", target, mode);
    g_free(target);
}

static void fishlim_gui_row_activated(GtkTreeView *tree, GtkTreePath *path, GtkTreeViewColumn *column, gpointer data) {
    GtkTreeModel *model = gtk_tree_view_get_model(tree);
    GtkTreeIter iter;
    char *target;

    if (!gtk_tree_model_get_iter(model, &iter, path))
        return;

    gtk_tree_model_get(model, &iter, 0, &target, -1);
    gtk_entry_set_text(GTK_ENTRY(fishlim_target_entry), target);
    g_free(target);
    fishlim_gui_refresh();
}

static void fishlim_gui_destroy(GtkWidget *widget, gpointer data) {
    fishlim_dialog = NULL;
    fishlim_target_entry = NULL;
    fishlim_key_entry = NULL;
    fishlim_mode_combo = NULL;
    fishlim_status_label = NULL;
    fishlim_store = NULL;
    fishlim_view = NULL;
}

static int handle_fishlim(char *word[], char *word_eol[], void *userdata) {
    GtkWidget *content, *grid, *view, *scroll, *buttons, *button;
    GtkCellRenderer *renderer;
    const char *target;

    target = *word_eol[2] ? word_eol[2] : zoitechat_get_info(ph, "channel");

    if (fishlim_dialog) {
        if (target)
            gtk_entry_set_text(GTK_ENTRY(fishlim_target_entry), target);
        gtk_window_present(GTK_WINDOW(fishlim_dialog));
        return ZOITECHAT_EAT_ZOITECHAT;
    }

    fishlim_dialog = gtk_dialog_new_with_buttons("FiSHLiM Key Manager", NULL, GTK_DIALOG_DESTROY_WITH_PARENT, "_Close", GTK_RESPONSE_CLOSE, NULL);
    gtk_window_set_default_size(GTK_WINDOW(fishlim_dialog), 520, 360);
    g_signal_connect(fishlim_dialog, "response", G_CALLBACK(gtk_widget_destroy), NULL);
    g_signal_connect(fishlim_dialog, "destroy", G_CALLBACK(fishlim_gui_destroy), NULL);

    content = gtk_dialog_get_content_area(GTK_DIALOG(fishlim_dialog));
    grid = gtk_grid_new();
    gtk_grid_set_row_spacing(GTK_GRID(grid), 8);
    gtk_grid_set_column_spacing(GTK_GRID(grid), 8);
    gtk_container_set_border_width(GTK_CONTAINER(grid), 12);
    gtk_box_pack_start(GTK_BOX(content), grid, TRUE, TRUE, 0);

    fishlim_target_entry = gtk_entry_new();
    if (target)
        gtk_entry_set_text(GTK_ENTRY(fishlim_target_entry), target);
    gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Target nick or channel"), 0, 0, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), fishlim_target_entry, 1, 0, 2, 1);

    fishlim_mode_combo = gtk_combo_box_text_new();
    gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(fishlim_mode_combo), "ECB");
    gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(fishlim_mode_combo), "CBC");
    gtk_combo_box_set_active(GTK_COMBO_BOX(fishlim_mode_combo), 1);
    gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Mode"), 0, 1, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), fishlim_mode_combo, 1, 1, 2, 1);
    gtk_grid_attach(GTK_GRID(grid), gtk_label_new("CBC may not work with older clients. Key exchange is private-message only."), 1, 2, 2, 1);

    fishlim_key_entry = gtk_entry_new();
    gtk_entry_set_visibility(GTK_ENTRY(fishlim_key_entry), FALSE);
    gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Key"), 0, 3, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), fishlim_key_entry, 1, 3, 2, 1);

    buttons = gtk_button_box_new(GTK_ORIENTATION_HORIZONTAL);
    gtk_button_box_set_layout(GTK_BUTTON_BOX(buttons), GTK_BUTTONBOX_END);
    gtk_grid_attach(GTK_GRID(grid), buttons, 0, 4, 3, 1);

    button = gtk_button_new_with_label("Set Key");
    g_signal_connect(button, "clicked", G_CALLBACK(fishlim_gui_set), NULL);
    gtk_container_add(GTK_CONTAINER(buttons), button);

    button = gtk_button_new_with_label("Delete Key");
    g_signal_connect(button, "clicked", G_CALLBACK(fishlim_gui_delete), NULL);
    gtk_container_add(GTK_CONTAINER(buttons), button);

    button = gtk_button_new_with_label("Private Message Key Exchange");
    g_signal_connect(button, "clicked", G_CALLBACK(fishlim_gui_keyx), NULL);
    gtk_container_add(GTK_CONTAINER(buttons), button);

    fishlim_status_label = gtk_label_new(NULL);
    gtk_label_set_xalign(GTK_LABEL(fishlim_status_label), 0.0);
    gtk_grid_attach(GTK_GRID(grid), fishlim_status_label, 0, 5, 3, 1);

    fishlim_store = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
    view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(fishlim_store));
    fishlim_view = view;
    renderer = gtk_cell_renderer_text_new();
    gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(view), -1, "Target", renderer, "text", 0, NULL);
    renderer = gtk_cell_renderer_text_new();
    gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(view), -1, "Mode", renderer, "text", 1, NULL);
    renderer = gtk_cell_renderer_text_new();
    gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(view), -1, "Status", renderer, "text", 2, NULL);
    g_signal_connect(view, "row-activated", G_CALLBACK(fishlim_gui_row_activated), NULL);

    scroll = gtk_scrolled_window_new(NULL, NULL);
    gtk_widget_set_vexpand(scroll, TRUE);
    gtk_container_add(GTK_CONTAINER(scroll), view);
    gtk_grid_attach(GTK_GRID(grid), scroll, 0, 6, 3, 1);

    g_signal_connect(fishlim_target_entry, "changed", G_CALLBACK(fishlim_gui_refresh_cb), NULL);
    fishlim_gui_refresh();

    gtk_widget_show_all(fishlim_dialog);
    return ZOITECHAT_EAT_ZOITECHAT;
}

/**
 * Command handler for /setkey
 */
static int handle_setkey(char *word[], char *word_eol[], void *userdata) {
    const char *nick;
    const char *key;
    enum fish_mode mode;

    /* Check syntax */
    if (*word[2] == '\0') {
        zoitechat_printf(ph, "%s\n", usage_setkey);
        return ZOITECHAT_EAT_ZOITECHAT;
    }

    if (*word[3] == '\0') {
        /* /setkey password */
        nick = zoitechat_get_info(ph, "channel");
        key = word_eol[2];
    } else {
        /* /setkey #channel password */
        nick = word[2];
        key = word_eol[3];
    }

    mode = FISH_ECB_MODE;
    if (g_ascii_strncasecmp("cbc:", key, 4) == 0) {
        key = key+4;
        mode = FISH_CBC_MODE;
    } else if (g_ascii_strncasecmp("ecb:", key, 4) == 0) {
        key = key+4;
    }

    /* Set password */
    if (keystore_store_key(nick, key, mode)) {
        zoitechat_printf(ph, "Stored key for %s (%s)\n", nick, fish_modes[mode]);
        if (mode == FISH_CBC_MODE)
            zoitechat_printf(ph, "Warning: CBC may not work with older clients.\n");
    } else {
        zoitechat_printf(ph, "\00305Failed to store key in addon_fishlim.conf\n");
    }

    return ZOITECHAT_EAT_ZOITECHAT;
}

/**
 * Command handler for /delkey
 */
static int handle_delkey(char *word[], char *word_eol[], void *userdata) {
    char *nick = NULL;
    int ctx_type = 0;

    /* Delete key from input */
    if (*word[2] != '\0') {
        nick = g_strstrip(g_strdup(word_eol[2]));
    } else { /* Delete key from current context */
        nick = g_strdup(zoitechat_get_info(ph, "channel"));
        ctx_type = zoitechat_list_int(ph, NULL, "type");

        /* Only allow channel or dialog */
        if (ctx_type < 2 || ctx_type > 3) {
            zoitechat_printf(ph, "%s\n", usage_delkey);
            return ZOITECHAT_EAT_ZOITECHAT;
        }
    }

    /* Delete the given nick from the key store */
    if (keystore_delete_nick(nick)) {
        zoitechat_printf(ph, "Deleted key for %s\n", nick);
    } else {
        zoitechat_printf(ph, "\00305Failed to delete key in addon_fishlim.conf!\n");
    }
    g_free(nick);

    return ZOITECHAT_EAT_ZOITECHAT;
}

static int handle_keyx(char *word[], char *word_eol[], void *userdata) {
    const char *target = word[2];
    zoitechat_context *query_ctx = NULL;
    char *pub_key, *priv_key;
    enum fish_mode mode = FISH_CBC_MODE;
    int ctx_type;

    if (*word[3]) {
        if (g_ascii_strcasecmp(word[3], "ECB") == 0)
            mode = FISH_ECB_MODE;
        else if (g_ascii_strcasecmp(word[3], "CBC") != 0) {
            zoitechat_printf(ph, "%s", usage_keyx);
            return ZOITECHAT_EAT_ALL;
        }
    }

    if (*target)
        query_ctx = find_context_on_network(target);
    else {
        target = zoitechat_get_info(ph, "channel");
        query_ctx = zoitechat_get_context (ph);
    }

    if (query_ctx) {
        g_assert(zoitechat_set_context(ph, query_ctx) == 1);
        ctx_type = zoitechat_list_int(ph, NULL, "type");
    }

    if ((query_ctx && ctx_type != 3) || (!query_ctx && !irc_is_query(target))) {
        zoitechat_printf(ph, "You can only exchange keys with individuals");
        return ZOITECHAT_EAT_ALL;
    }

    if (dh1080_generate_key(&priv_key, &pub_key)) {
        g_hash_table_replace (pending_exchanges, g_ascii_strdown(target, -1), priv_key);

        zoitechat_commandf(ph, "quote NOTICE %s :DH1080_INIT %s%s", target, pub_key, (mode == FISH_CBC_MODE) ? " CBC" : "");
        zoitechat_printf(ph, "Sent public key to %s (%s), waiting for reply...", target, fish_modes[mode]);
        if (mode == FISH_CBC_MODE)
            zoitechat_printf(ph, "Warning: CBC may not work with older clients.");

        g_free(pub_key);
    } else {
        zoitechat_printf(ph, "Failed to generate keys");
    }

    return ZOITECHAT_EAT_ALL;
}

/**
 * Command handler for /topic+
 */
static int handle_crypt_topic(char *word[], char *word_eol[], void *userdata) {
    const char *target;
    const char *topic = word_eol[2];
    enum fish_mode mode;
    GString *command;
    GSList *encrypted_list;

    if (!*topic) {
        zoitechat_printf(ph, "%s", usage_topic);
        return ZOITECHAT_EAT_ALL;
    }

    if (zoitechat_list_int(ph, NULL, "type") != 2) {
        zoitechat_printf(ph, "Please change to the channel window where you want to set the topic!");
        return ZOITECHAT_EAT_ALL;
    }

    target = zoitechat_get_info(ph, "channel");

    /* Check if we can encrypt */
    if (!fish_nick_has_key(target)) {
        zoitechat_printf(ph, "/topic+ error, no key found for %s", target);
        return ZOITECHAT_EAT_ALL;
    }

    command = g_string_new("");
    g_string_printf(command, "TOPIC %s +OK ", target);

    encrypted_list = fish_encrypt_for_nick(target, topic, &mode, get_prefix_length() + command->len);
    if (!encrypted_list) {
        g_string_free(command, TRUE);
        zoitechat_printf(ph, "/topic+ error, can't encrypt %s", target);
        return ZOITECHAT_EAT_ALL;
    }

    zoitechat_commandf(ph, "%s%s", command->str, (char *) encrypted_list->data);

    g_string_free(command, TRUE);
    g_slist_free_full(encrypted_list, g_free);

    return ZOITECHAT_EAT_ALL;
}

/**
 * Command handler for /notice+
 */
static int handle_crypt_notice(char *word[], char *word_eol[], void *userdata) {
    const char *target = word[2];
    const char *notice = word_eol[3];
    char *notice_flag;
    enum fish_mode mode;
    GString *command;
    GSList *encrypted_list, *encrypted_item;

    if (!*target || !*notice) {
        zoitechat_printf(ph, "%s", usage_notice);
        return ZOITECHAT_EAT_ALL;
    }

    /* Check if we can encrypt */
    if (!fish_nick_has_key(target)) {
        zoitechat_printf(ph, "/notice+ error, no key found for %s.", target);
        return ZOITECHAT_EAT_ALL;
    }

    command = g_string_new("");
    g_string_printf(command, "quote NOTICE %s :+OK ", target);

    encrypted_list = fish_encrypt_for_nick(target, notice, &mode, get_prefix_length() + command->len);
    if (!encrypted_list) {
        g_string_free(command, TRUE);
        zoitechat_printf(ph, "/notice+ error, can't encrypt %s", target);
        return ZOITECHAT_EAT_ALL;
    }

    notice_flag = g_strconcat("[", fish_modes[mode], "] ", notice, NULL);
    zoitechat_emit_print(ph, "Notice Send", target, notice_flag);

    /* Send encrypted messages */
    encrypted_item = encrypted_list;
    while (encrypted_item) {
        zoitechat_commandf(ph, "%s%s", command->str, (char *) encrypted_item->data);

        encrypted_item = encrypted_item->next;
    }

    g_free(notice_flag);
    g_string_free(command, TRUE);
    g_slist_free_full(encrypted_list, g_free);

    return ZOITECHAT_EAT_ALL;
}

/**
 * Command handler for /msg+
 */
static int handle_crypt_msg(char *word[], char *word_eol[], void *userdata) {
    const char *target = word[2];
    const char *message = word_eol[3];
    char *message_flag;
    char *prefix;
    zoitechat_context *query_ctx;
    enum fish_mode mode;
    GString *command;
    GSList *encrypted_list, *encrypted_item;

    if (!*target || !*message) {
        zoitechat_printf(ph, "%s", usage_msg);
        return ZOITECHAT_EAT_ALL;
    }

    /* Check if we can encrypt */
    if (!fish_nick_has_key(target)) {
        zoitechat_printf(ph, "/msg+ error, no key found for %s", target);
        return ZOITECHAT_EAT_ALL;
    }

    command = g_string_new("");
    g_string_printf(command, "PRIVMSG %s :+OK ", target);

    encrypted_list = fish_encrypt_for_nick(target, message, &mode, get_prefix_length() + command->len);
    if (!encrypted_list) {
        g_string_free(command, TRUE);
        zoitechat_printf(ph, "/msg+ error, can't encrypt %s", target);
        return ZOITECHAT_EAT_ALL;
    }

    /* Send encrypted messages */
    encrypted_item = encrypted_list;
    while (encrypted_item) {
        zoitechat_commandf(ph, "%s%s", command->str, (char *) encrypted_item->data);

        encrypted_item = encrypted_item->next;
    }

    g_string_free(command, TRUE);
    g_slist_free_full(encrypted_list, g_free);

    query_ctx = find_context_on_network(target);
    if (query_ctx) {
        g_assert(zoitechat_set_context(ph, query_ctx) == 1);

        prefix = get_my_own_prefix();

        /* Add encrypted flag */
        message_flag = g_strconcat("[", fish_modes[mode], "] ", message, NULL);
        zoitechat_emit_print(ph, "Your Message", zoitechat_get_info(ph, "nick"), message_flag, prefix, NULL);
        g_free(prefix);
        g_free(message_flag);
    } else {
        zoitechat_emit_print(ph, "Message Send", target, message);
    }

    return ZOITECHAT_EAT_ALL;
}

static int handle_crypt_me(char *word[], char *word_eol[], void *userdata) {
    const char *channel = zoitechat_get_info(ph, "channel");
    enum fish_mode mode;
    GString *command;
    GSList *encrypted_list, *encrypted_item;

    /* Check if we can encrypt */
    if (!fish_nick_has_key(channel)) {
        return ZOITECHAT_EAT_NONE;
    }

    command = g_string_new("");
    g_string_printf(command, "PRIVMSG %s :\001ACTION +OK ", channel);

    /* 2 = ' \001' */
    encrypted_list = fish_encrypt_for_nick(channel, word_eol[2], &mode, get_prefix_length() + command->len + 2);
    if (!encrypted_list) {
        g_string_free(command, TRUE);
        zoitechat_printf(ph, "/me error, can't encrypt %s", channel);
        return ZOITECHAT_EAT_ALL;
    }

    zoitechat_emit_print(ph, "Your Action", zoitechat_get_info(ph, "nick"), word_eol[2], NULL);

    /* Send encrypted messages */
    encrypted_item = encrypted_list;
    while (encrypted_item) {
        zoitechat_commandf(ph, "%s%s \001", command->str, (char *) encrypted_item->data);

        encrypted_item = encrypted_item->next;
    }

    g_string_free(command, TRUE);
    g_slist_free_full(encrypted_list, g_free);

    return ZOITECHAT_EAT_ALL;
}

/**
 * Returns the plugin name version information.
 */
void zoitechat_plugin_get_info(const char **name, const char **desc,
                           const char **version, void **reserved) {
    *name = plugin_name;
    *desc = plugin_desc;
    *version = plugin_version;
}

/**
 * Plugin entry point.
 */
int zoitechat_plugin_init(zoitechat_plugin *plugin_handle,
                      const char **name,
                      const char **desc,
                      const char **version,
                      char *arg) {
    ph = plugin_handle;

    /* Send our info to ZoiteChat */
    *name = plugin_name;
    *desc = plugin_desc;
    *version = plugin_version;

    /* Register commands */
    zoitechat_hook_command(ph, "FISHLIM", ZOITECHAT_PRI_NORM, handle_fishlim, "Usage: FISHLIM, opens the FiSHLiM key manager", NULL);
    zoitechat_hook_command(ph, "SETKEY", ZOITECHAT_PRI_NORM, handle_setkey, usage_setkey, NULL);
    zoitechat_hook_command(ph, "DELKEY", ZOITECHAT_PRI_NORM, handle_delkey, usage_delkey, NULL);
    zoitechat_hook_command(ph, "KEYX", ZOITECHAT_PRI_NORM, handle_keyx, usage_keyx, NULL);
    zoitechat_hook_command(ph, "TOPIC+", ZOITECHAT_PRI_NORM, handle_crypt_topic, usage_topic, NULL);
    zoitechat_hook_command(ph, "NOTICE+", ZOITECHAT_PRI_NORM, handle_crypt_notice, usage_notice, NULL);
    zoitechat_hook_command(ph, "MSG+", ZOITECHAT_PRI_NORM, handle_crypt_msg, usage_msg, NULL);
    zoitechat_hook_command(ph, "ME", ZOITECHAT_PRI_NORM, handle_crypt_me, NULL, NULL);

    /* Add handlers */
    zoitechat_hook_command(ph, "", ZOITECHAT_PRI_NORM, handle_outgoing, NULL, NULL);
    zoitechat_hook_server(ph, "NOTICE", ZOITECHAT_PRI_HIGHEST, handle_keyx_notice, NULL);
    zoitechat_hook_server_attrs(ph, "NOTICE", ZOITECHAT_PRI_NORM, handle_incoming, NULL);
    zoitechat_hook_server_attrs(ph, "PRIVMSG", ZOITECHAT_PRI_NORM, handle_incoming, NULL);
    zoitechat_hook_server_attrs(ph, "TOPIC", ZOITECHAT_PRI_NORM, handle_incoming, NULL);
    zoitechat_hook_server_attrs(ph, "332", ZOITECHAT_PRI_NORM, handle_incoming, NULL);

    if (!fish_init()) {
        zoitechat_printf(ph, "FiSHLiM failed to initialize crypto backend");
        return 0;
    }

    if (!dh1080_init()) {
        zoitechat_printf(ph, "FiSHLiM failed to initialize DH1080");
        return 0;
    }

    pending_exchanges = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);

    zoitechat_command(ph, "MENU ADD \"Window/FiSHLiM Key Manager\" \"FISHLIM\"");
    zoitechat_command(ph, "MENU ADD \"$NICK/FiSHLiM Key Manager\" \"FISHLIM %s\"");

    zoitechat_printf(ph, "%s plugin loaded\n", plugin_name);
    /* Return success */
    return 1;
}

int zoitechat_plugin_deinit(void) {
    zoitechat_command(ph, "MENU DEL \"Window/FiSHLiM Key Manager\"");
    zoitechat_command(ph, "MENU DEL \"$NICK/FiSHLiM Key Manager\"");
    if (fishlim_dialog)
        gtk_widget_destroy(fishlim_dialog);
    g_clear_pointer(&pending_exchanges, g_hash_table_destroy);
    dh1080_deinit();
    fish_deinit();

    zoitechat_printf(ph, "%s plugin unloaded\n", plugin_name);
    return 1;
}
