/*
 * Copyright (c) KylinSoft  Co., Ltd. 2024. All rights reserved.
 *
 * kaiming is licensed under the GPL v2.0+.
 *
 * See the LICENSE file for more details.
 */

#include "KMRunnerOnce.h"

#include "common/KMLogger.h"
#include "common/KMUtil.h"
#include "common/KMConfigData.h"
#include "common/KMCrun.h"

/**
 * @brief 应用是否已运行
 * @return true 成功 false 失败
 */
bool KMRunnerOnce::isAlreadyRun(const std::string &appId, std::string &containerid)
{
    if (appId.empty())
    {
        return false;
    }

    vector<ContainerListItem> items;
    vector<string> args = { "list", "--format=json" };
    if (!KMCrun::exec<vector<ContainerListItem>>(args, items))
    {
        return false;
    }

    for (const auto &item : items)
    {
        std::vector<std::string> argsAppid = { "state", item.id };
        State itemAppid;
        if (!KMCrun::exec<State>(argsAppid, itemAppid))
        {
            continue;
        }

        if (itemAppid.annotations.value_or(std::map<std::string, std::string>{})["kaiming.app.id"] == appId)
        {
            containerid = item.id;
            return true;
        }
    }

    return false;
}

/**
 * @brief 再次运行
 * @param containerid 容器id
 * @param commandArgs 运行命令及参数
 * @return true 成功 false 失败
 */
bool KMRunnerOnce::runOnce(const std::string &containerid, const std::string &commandArgs)
{
    if (commandArgs.empty())
    {
        KMError("run command is empty");
        return false;
    }

    std::string user = std::string("--user=") + to_string(getuid()) + std::string(":") + to_string(getgid());
    vector<std::string> enterArgs = { "exec", user, containerid };
    enterArgs.emplace_back("/bin/bash");
    enterArgs.emplace_back("--login");
    enterArgs.emplace_back("-e");
    enterArgs.emplace_back("-c");
    enterArgs.emplace_back(commandArgs);

    if (!KMCrun::exec(enterArgs, false))
    {
        KMError("crun exec commands failds");
        return false;
    }

    return true;
}