#include "install.h"
#include "resource.h"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <iostream>

namespace fs = boost::filesystem;

bool CInstallBinary::startInstall(const CmdResult& result)
{
    CResource res;
    auto shell_template = res.getShellTemplate();
    auto desktop_tempte = res.getDesktopTemplate();

    auto file_name = fs::path(result.binary).filename().string();
    // 写临时文件
    char* home = std::getenv("HOME");
    fs::path homep(home);
    fs::path work_path = fs::path(homep).append(".config").append("PackBinary");
    fs::create_directories(work_path);

    fs::path temp_shell = fs::path(result.binary).parent_path().append(file_name + "_run.sh");
    fs::path temp_desktop = fs::path(work_path).append(file_name + ".desktop");
    // fs::path dest_dir = fs::path(result.purpose_dir).append(file_name);
    // fs::create_directories(dest_dir);

    auto write_file = [](const std::string& content,
                         const std::string& file) -> bool {
        std::ofstream of(file);
        if (!of.is_open()) {
            std::cerr << "file not opened: " << file << std::endl;
            return false;
        }
        of << content;
        of.close();
        return true;
    };

    boost::replace_all(shell_template, "replace_str", file_name);
    boost::replace_all(desktop_tempte, "re_name", file_name);
    boost::replace_all(desktop_tempte, "re_describe", "default");
    boost::replace_all(desktop_tempte, "re_path", temp_shell.string()); 
    boost::replace_all(desktop_tempte, "re_icon", result.ico);
    boost::replace_all(desktop_tempte, "re_category", result.category);

    if (!write_file(shell_template, temp_shell.string())) {
        return false;
    }

    std::string cmd("chmod +x " + temp_shell.string());
    std::cout << cmd << " Ret:" << std::system(cmd.c_str()) << std::endl;

    if (!write_file(desktop_tempte, temp_desktop.string())) {
        return false;
    }

    cmd.clear();
    cmd = "pkexec cp " + temp_desktop.string() + " /usr/share/applications";
    std::cout << cmd << " Ret:" << std::system(cmd.c_str()) << std::endl;

    return true;
}