#include <string>
#include <vector>
#include <fstream>
#include <filesystem>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <unistd.h>

#include "archive_tgz.hpp"

namespace common {

namespace fs = std::filesystem;

// Escape string for shell command
static std::string shellEscape(const std::string& str) {
    std::string result;
    result.reserve(str.length() + 20);
    result += "'";
    for (char c : str) {
        if (c == '\'') {
            result += "'\\''";
        } else {
            result += c;
        }
    }
    result += "'";
    return result;
}

bool pack_tgz(const std::string& folderPath, const std::string& archivePath) {
    // Use system tar to create gzipped tarball
    std::ostringstream cmd;
    cmd << "tar -czf ";
    cmd << shellEscape(archivePath);
    cmd << " -C ";
    cmd << shellEscape(folderPath);
    cmd << " .";
    int ret = std::system(cmd.str().c_str());
    return ret == 0;
}

bool unpack_tgz(const std::string& archivePath, const std::string& outDir) {
    fs::create_directories(outDir);
    std::ostringstream cmd;
    cmd << "tar -xzf ";
    cmd << shellEscape(archivePath);
    cmd << " -C ";
    cmd << shellEscape(outDir);
    int ret = std::system(cmd.str().c_str());
    return ret == 0;
}

} // namespace common 