/*
 * GnomeSettingsVault - A GNOME configuration backup utility v0.3.2
 */

#include "MainWindow.hpp"
#include <iostream>
#include <filesystem>
#include <archive.h>
#include <archive_entry.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <set>
#include <glibmm/miscutils.h>
#include <glibmm/fileutils.h>

namespace fs = std::filesystem;

MainWindow::MainWindow()
: m_HeaderBar(), m_MainLayout(Gtk::ORIENTATION_VERTICAL, 0), m_Notebook(),
  m_BottomBox(Gtk::ORIENTATION_HORIZONTAL, 10), m_StatusLabel("Ready."), 
  m_CheckDebugMode("Write Debug Log to Disk (~/GnomeSettingsVault.log)"), m_VBoxBackup(Gtk::ORIENTATION_VERTICAL, 10),
  m_LabelBackupInstruction("<span size='large' weight='bold'>Backup</span>"),
  m_CheckThemesBackup("GTK Themes"), m_CheckIconsBackup("Icons"),
  m_CheckWallpapersBackup("Wallpapers"), m_CheckExtensionsBackup("GNOME Extensions"),
  m_CheckDconfBackup("GNOME Settings"), m_ButtonBackup("Start Backup"),
  m_VBoxRestore(Gtk::ORIENTATION_VERTICAL, 10),
  m_LabelRestoreInstruction("<span size='large' weight='bold'>Restore from Vault</span>"),
  m_ButtonSelectVault("Select .gbk Vault File"), m_LabelSelectedVault("No vault selected"),
  m_CheckThemesRestore("GTK Themes"), m_CheckIconsRestore("Icons"),
  m_CheckWallpapersRestore("Wallpapers"), m_CheckExtensionsRestore("GNOME Extensions"),
  m_CheckDconfRestore("GNOME Settings"), m_CheckDryRunRestore("Dry Run"),
  m_ButtonRestore("Start Restore"), m_WorkerRunning(false), m_JobSuccess(true), 
  m_IsDebugMode(false), m_LastJobWasRestore(false)
{
    m_Dispatcher.connect(sigc::mem_fun(*this, &MainWindow::on_dispatcher_ping));
    set_default_size(1000, 700);
    m_HeaderBar.set_title("GnomeSettingsVault 0.3.2");
    m_HeaderBar.set_show_close_button(true);
    set_titlebar(m_HeaderBar);
    
    set_wmclass("gnome-vault", "GnomeSettingsVault");

    m_LabelBackupInstruction.set_use_markup(true);
    m_LabelRestoreInstruction.set_use_markup(true);

    m_RefTextBuffer = Gtk::TextBuffer::create();
    m_LogView.set_buffer(m_RefTextBuffer);
    m_LogView.set_editable(false);
    m_LogView.override_background_color(Gdk::RGBA("#1e1e1e")); 
    m_LogView.override_color(Gdk::RGBA("#dcdcdc"));
    
    m_RefTextBuffer->create_mark("last_line", m_RefTextBuffer->end());
    m_ScrolledWindow.add(m_LogView);
    m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS);

    m_VBoxBackup.set_border_width(20);
    m_VBoxBackup.pack_start(m_LabelBackupInstruction, Gtk::PACK_SHRINK);
    m_VBoxBackup.pack_start(m_CheckThemesBackup, Gtk::PACK_SHRINK);
    m_VBoxBackup.pack_start(m_CheckIconsBackup, Gtk::PACK_SHRINK);
    m_VBoxBackup.pack_start(m_CheckWallpapersBackup, Gtk::PACK_SHRINK);
    m_VBoxBackup.pack_start(m_CheckExtensionsBackup, Gtk::PACK_SHRINK);
    m_VBoxBackup.pack_start(m_CheckDconfBackup, Gtk::PACK_SHRINK);
    m_VBoxBackup.pack_end(m_ButtonBackup, Gtk::PACK_SHRINK);
    
    m_VBoxRestore.set_border_width(20);
    m_VBoxRestore.pack_start(m_LabelRestoreInstruction, Gtk::PACK_SHRINK);
    m_VBoxRestore.pack_start(m_ButtonSelectVault, Gtk::PACK_SHRINK);
    m_VBoxRestore.pack_start(m_LabelSelectedVault, Gtk::PACK_SHRINK);
    m_VBoxRestore.pack_start(m_CheckThemesRestore, Gtk::PACK_SHRINK);
    m_VBoxRestore.pack_start(m_CheckIconsRestore, Gtk::PACK_SHRINK);
    m_VBoxRestore.pack_start(m_CheckWallpapersRestore, Gtk::PACK_SHRINK);
    m_VBoxRestore.pack_start(m_CheckExtensionsRestore, Gtk::PACK_SHRINK);
    m_VBoxRestore.pack_start(m_CheckDconfRestore, Gtk::PACK_SHRINK);
    m_VBoxRestore.pack_start(m_CheckDryRunRestore, Gtk::PACK_SHRINK);
    m_VBoxRestore.pack_end(m_ButtonRestore, Gtk::PACK_SHRINK);

    m_Notebook.append_page(m_VBoxBackup, "Backup");
    m_Notebook.append_page(m_VBoxRestore, "Restore");
    
    m_BottomBox.set_border_width(10);
    m_BottomBox.pack_start(m_StatusLabel, Gtk::PACK_EXPAND_WIDGET);
    m_BottomBox.pack_end(m_CheckDebugMode, Gtk::PACK_SHRINK);

    m_MainLayout.pack_start(m_Notebook, Gtk::PACK_SHRINK);
    m_MainLayout.pack_start(m_ScrolledWindow, Gtk::PACK_EXPAND_WIDGET);
    m_MainLayout.pack_start(m_BottomBox, Gtk::PACK_SHRINK);

    m_ButtonBackup.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_button_backup_clicked));
    m_ButtonRestore.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_button_restore_clicked));
    m_ButtonSelectVault.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_button_select_vault_clicked));

    add(m_MainLayout);
    show_all_children();
}

MainWindow::~MainWindow() {}

void MainWindow::send_notification(const std::string& title, const std::string& body) {
    auto app = Gtk::Application::get_default();
    auto notification = Gio::Notification::create(title);
    notification->set_body(body);
    app->send_notification(notification);
}

void MainWindow::scan_vault_contents(const std::string& path) {
    struct archive *a = archive_read_new();
    struct archive_entry *entry;
    archive_read_support_format_all(a);
    archive_read_support_filter_all(a);
    std::set<std::string> found;
    if (archive_read_open_filename(a, path.c_str(), 10240) == ARCHIVE_OK) {
        while (archive_read_next_header(a, &entry) == ARCHIVE_OK) {
            std::string p = archive_entry_pathname(entry);
            if (p.find("themes_") != std::string::npos) found.insert("themes");
            if (p.find("icons_") != std::string::npos) found.insert("icons");
            if (p.find("wallpapers.tar.gz") != std::string::npos) found.insert("wallpapers");
            if (p.find("extensions.tar.gz") != std::string::npos) found.insert("extensions");
            if (p.find("settings.ini") != std::string::npos) found.insert("dconf");
        }
    }
    archive_read_free(a);
    m_CheckThemesRestore.set_active(found.count("themes"));
    m_CheckIconsRestore.set_active(found.count("icons"));
    m_CheckWallpapersRestore.set_active(found.count("wallpapers"));
    m_CheckExtensionsRestore.set_active(found.count("extensions"));
    m_CheckDconfRestore.set_active(found.count("dconf"));
}

void MainWindow::on_button_select_vault_clicked() {
    Gtk::FileChooserDialog dialog("Choose vault", Gtk::FILE_CHOOSER_ACTION_OPEN);
    dialog.set_transient_for(*this);
    dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);
    dialog.add_button("_Open", Gtk::RESPONSE_OK);
    if (dialog.run() == Gtk::RESPONSE_OK) {
        m_SelectedVaultPath = dialog.get_filename();
        m_LabelSelectedVault.set_text("Selected: " + fs::path(m_SelectedVaultPath).filename().string());
        scan_vault_contents(m_SelectedVaultPath);
        add_log_ui("Vault loaded.");
    }
}

void MainWindow::queue_log(const std::string& message) {
    if (m_IsDebugMode) {
        std::ofstream log_file(std::string(std::getenv("HOME")) + "/GnomeSettingsVault.log", std::ios::app);
        if (log_file.is_open()) { log_file << message << std::endl; log_file.close(); }
    }
    std::lock_guard<std::mutex> lock(m_LogMutex);
    m_LogQueue.push(message);
    m_Dispatcher.emit();
}

void MainWindow::on_dispatcher_ping() {
    std::lock_guard<std::mutex> lock(m_LogMutex);
    while (!m_LogQueue.empty()) {
        std::string msg = m_LogQueue.front();
        m_LogQueue.pop();
        if (msg == "__UNLOCK_UI__") {
            set_ui_locked(false);
            send_notification("Job Finished", m_JobSuccess ? "Successfully completed." : "Errors detected.");
            if (m_JobSuccess && m_LastJobWasRestore) {
                Gtk::MessageDialog dialog(*this, "Restore Complete", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO);
                dialog.set_secondary_text("Settings restored. Restart GNOME session now?");
                if (dialog.run() == Gtk::RESPONSE_YES) system("gnome-session-quit --logout --no-prompt &");
            }
        } else {
            add_log_ui(msg);
        }
    }
}

void MainWindow::add_log_ui(const std::string& message) {
    m_RefTextBuffer->insert(m_RefTextBuffer->end(), message + "\n");
    auto mark = m_RefTextBuffer->get_mark("last_line");
    m_RefTextBuffer->move_mark(mark, m_RefTextBuffer->end());
    if (m_LogView.get_realized()) m_LogView.scroll_to(mark);
}

void MainWindow::set_ui_locked(bool locked) {
    m_ButtonBackup.set_sensitive(!locked);
    m_ButtonRestore.set_sensitive(!locked);
    m_ButtonSelectVault.set_sensitive(!locked);
    m_CheckDebugMode.set_sensitive(!locked);
    if (!locked) {
        m_StatusLabel.override_color(m_JobSuccess ? Gdk::RGBA("#44ff44") : Gdk::RGBA("#ff4444"));
        m_StatusLabel.set_text(m_JobSuccess ? "Job Successful." : "Job Failed.");
    }
}

void MainWindow::run_backup_job(JobConfig config, std::string home_dir) {
    m_JobSuccess = true; std::error_code ec;
    queue_log("--- Starting Backup ---");
    
    char tpl[] = "/tmp/gvault_pack_XXXXXX";
    if (mkdtemp(tpl) == nullptr) {
        queue_log("!!! ERROR: Failed to create secure temp directory.");
        m_JobSuccess = false; 
        m_WorkerRunning = false;
        queue_log("__UNLOCK_UI__");
        return;
    }
    std::string temp_dir(tpl);

    auto pack_h = [&](const std::string& p, const std::string& n) {
        if (fs::exists(p)) if(!create_tar_archive(p, temp_dir + "/" + n, false)) m_JobSuccess = false;
    };

    if (config.themes) { pack_h(home_dir + "/.themes", "themes_legacy.tar.gz"); pack_h(home_dir + "/.local/share/themes", "themes_xdg.tar.gz"); }
    if (config.icons) { pack_h(home_dir + "/.icons", "icons_legacy.tar.gz"); pack_h(home_dir + "/.local/share/icons", "icons_xdg.tar.gz"); }
    if (config.wallpapers) { std::string w = get_wallpaper_directory(); if(!w.empty()) pack_h(w, "wallpapers.tar.gz"); }
    if (config.extensions) pack_h(home_dir + "/.local/share/gnome-shell/extensions", "extensions.tar.gz");
    
    if (config.dconf) { 
        queue_log("[BACKUP] Exporting GNOME Settings...");
        if (system(("dconf dump / > '" + temp_dir + "/settings.ini'").c_str()) != 0) m_JobSuccess = false; 
    }

    if(!create_tar_archive(temp_dir, home_dir + "/" + config.vault_name + ".gbk", true)) m_JobSuccess = false;
    fs::remove_all(temp_dir, ec);
    queue_log("__UNLOCK_UI__");
    m_WorkerRunning = false;
}

void MainWindow::on_button_backup_clicked() {
    Gtk::MessageDialog dialog(*this, "Vault Name", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_OK_CANCEL);
    Gtk::Entry entry; entry.set_text("GnomeVaultBackup");
    dialog.get_content_area()->pack_start(entry, Gtk::PACK_SHRINK);
    dialog.show_all_children();
    if (dialog.run() == Gtk::RESPONSE_OK) {
        m_IsDebugMode = m_CheckDebugMode.get_active();
        m_LastJobWasRestore = false;
        set_ui_locked(true); m_WorkerRunning = true;
        m_StatusLabel.set_text("Backup in progress...");
        JobConfig cfg;
        cfg.themes = m_CheckThemesBackup.get_active(); cfg.icons = m_CheckIconsBackup.get_active();
        cfg.wallpapers = m_CheckWallpapersBackup.get_active(); cfg.extensions = m_CheckExtensionsBackup.get_active();
        cfg.dconf = m_CheckDconfBackup.get_active(); cfg.dry_run = false; cfg.vault_name = entry.get_text();
        std::thread(&MainWindow::run_backup_job, this, cfg, std::string(std::getenv("HOME"))).detach();
    }
}

void MainWindow::run_restore_job(JobConfig config, std::string home_dir) {
    m_JobSuccess = true; std::error_code ec;
    queue_log("--- Starting Restore ---");
    
    auto settings = Gio::Settings::create("org.gnome.shell");
    if (config.extensions && !config.dry_run) settings->set_boolean("disable-user-extensions", true);

    char tpl[] = "/tmp/gvault_unpack_XXXXXX";
    if (mkdtemp(tpl) == nullptr) {
        queue_log("!!! ERROR: Failed to create secure temp directory.");
        m_JobSuccess = false; 
        if (config.extensions && !config.dry_run) settings->set_boolean("disable-user-extensions", false);
        m_WorkerRunning = false;
        queue_log("__UNLOCK_UI__");
        return;
    }
    std::string temp_unpack(tpl);

    if (!extract_tar_archive(config.custom_restore_path, temp_unpack, false, false)) m_JobSuccess = false;

    auto atomic_res = [&](const std::string& n, const std::string& lp, const std::string& lbl) {
        std::string arch = temp_unpack + "/" + n + ".tar.gz";
        if (fs::exists(arch)) {
            queue_log("[RESTORE] Swapping " + lbl + "...");
            std::string sh = lp + "_vault_new"; std::string od = lp + "_vault_old";
            fs::remove_all(sh, ec); fs::remove_all(od, ec); fs::create_directories(sh);
            
            if (extract_tar_archive(arch, sh, config.dry_run, false)) {
                if (!config.dry_run) {
                    sync();
                    bool had_old = fs::exists(lp);
                    if (had_old) fs::rename(lp, od, ec);
                    fs::rename(sh, lp, ec);
                    if (ec) { 
                        queue_log("!!! FAIL: Rolling back " + lbl); 
                        if (had_old) fs::rename(od, lp, ec);
                        m_JobSuccess = false; 
                    } else fs::remove_all(od, ec);
                }
            } else m_JobSuccess = false;
        }
    };

    if (config.themes) { atomic_res("themes_legacy", home_dir + "/.themes", "Themes (Legacy)"); atomic_res("themes_xdg", home_dir + "/.local/share/themes", "Themes (XDG)"); }
    if (config.icons) { atomic_res("icons_legacy", home_dir + "/.icons", "Icons (Legacy)"); atomic_res("icons_xdg", home_dir + "/.local/share/icons", "Icons (XDG)"); }
    if (config.extensions) atomic_res("extensions", home_dir + "/.local/share/gnome-shell/extensions", "Extensions");
    
    if (config.wallpapers && fs::exists(temp_unpack + "/wallpapers.tar.gz")) {
        queue_log("[RESTORE] Restoring Wallpapers...");
        if (!extract_tar_archive(temp_unpack + "/wallpapers.tar.gz", "/", config.dry_run, true)) m_JobSuccess = false;
    }

    if (config.dconf && fs::exists(temp_unpack + "/settings.ini") && !config.dry_run) {
        queue_log("[RESTORE] Injecting Dconf...");
        if (system(("dconf load / < '" + temp_unpack + "/settings.ini'").c_str()) != 0) m_JobSuccess = false;
    }

    if (config.extensions && !config.dry_run) settings->set_boolean("disable-user-extensions", false);
    fs::remove_all(temp_unpack, ec);
    queue_log("__UNLOCK_UI__");
}

void MainWindow::on_button_restore_clicked() {
    if (m_SelectedVaultPath.empty()) return;
    m_IsDebugMode = m_CheckDebugMode.get_active();
    m_LastJobWasRestore = true; set_ui_locked(true); m_WorkerRunning = true;
    m_StatusLabel.set_text("Restore in progress...");
    JobConfig cfg;
    cfg.themes = m_CheckThemesRestore.get_active(); cfg.icons = m_CheckIconsRestore.get_active();
    cfg.wallpapers = m_CheckWallpapersRestore.get_active(); cfg.extensions = m_CheckExtensionsRestore.get_active();
    cfg.dconf = m_CheckDconfRestore.get_active(); cfg.dry_run = m_CheckDryRunRestore.get_active(); cfg.custom_restore_path = m_SelectedVaultPath;
    std::thread(&MainWindow::run_restore_job, this, cfg, std::string(std::getenv("HOME"))).detach();
}

bool MainWindow::create_tar_archive(const std::string& s, const std::string& o, bool strip) {
    struct archive *a = archive_write_new();
    archive_write_add_filter_gzip(a); archive_write_set_format_pax_restricted(a);
    archive_write_open_filename(a, o.c_str());
    fs::path bp = fs::absolute(s); bool ok = true;
    for (const auto& d : fs::recursive_directory_iterator(bp, fs::directory_options::skip_permission_denied)) {
        std::string f = d.path().string(); std::string st = strip ? fs::relative(d.path(), bp).string() : f;
        if (st == "." || st == "..") continue;
        struct archive_entry *e = archive_entry_new(); archive_entry_set_pathname(e, st.c_str());
        struct stat sbuf; if (lstat(f.c_str(), &sbuf) != 0) { archive_entry_free(e); ok = false; continue; }
        archive_entry_copy_stat(e, &sbuf);
        if (S_ISLNK(sbuf.st_mode)) { char t[4096]; ssize_t l = readlink(f.c_str(), t, 4095); if (l != -1) { t[l]='\0'; archive_entry_set_symlink(e, t); } }
        archive_write_header(a, e);
        queue_log("  -> Packed: " + st);
        if (S_ISREG(sbuf.st_mode)) { int fd = ::open(f.c_str(), O_RDONLY); if (fd >= 0) { char b[65536]; ssize_t l; while ((l = ::read(fd, b, 65536)) > 0) archive_write_data(a, b, l); ::close(fd); } else ok = false; }
        archive_entry_free(e);
    }
    archive_write_close(a); archive_write_free(a); return ok;
}

bool MainWindow::extract_tar_archive(const std::string& ap, const std::string& ds, bool dr, bool abs) {
    struct archive *a = archive_read_new();
    archive_read_support_format_all(a); archive_read_support_filter_all(a);
    if (archive_read_open_filename(a, ap.c_str(), 10240) != ARCHIVE_OK) return false;
    struct archive_entry *e; bool ok = true;
    while (archive_read_next_header(a, &e) == ARCHIVE_OK) {
        std::string sp = archive_entry_pathname(e);
        if (!abs) {
            size_t p = sp.find("/themes/"); if (p == std::string::npos) p = sp.find("/icons/");
            if (p == std::string::npos) p = sp.find("/extensions/");
            if (p != std::string::npos) { size_t s = sp.find('/', p + 1); if (s != std::string::npos) sp = sp.substr(s + 1); }
        }
        std::string t = abs ? archive_entry_pathname(e) : ds + "/" + sp;
        archive_entry_set_pathname(e, t.c_str());
        if (dr) { queue_log("  -> [DRY] " + t); archive_read_data_skip(a); }
        else if (archive_read_extract(a, e, ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_UNLINK) != ARCHIVE_OK) { if (!fs::is_directory(t)) ok = false; }
        else queue_log("  -> Restored: " + t);
    }
    archive_read_close(a); archive_read_free(a); return ok;
}

std::string MainWindow::get_wallpaper_directory() {
    char b[256]; std::string r = "";
    FILE* p = popen("gsettings get org.gnome.desktop.background picture-uri-dark 2>/dev/null", "r");
    if (p) { while (fgets(b, 256, p)) r += b; pclose(p); }
    size_t f = r.find("file://");
    if (f != std::string::npos) {
        std::string path = r.substr(f + 7);
        path.erase(std::remove(path.begin(), path.end(), '\''), path.end());
        path.erase(std::remove(path.begin(), path.end(), '\n'), path.end());
        return fs::path(path).parent_path().string();
    }
    return "";
}
