#!/usr/bin/env python3
# encoding=utf-8
# 描述：组件维护工具
# Copyright (c) 2024 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os
import argparse

import yaml

from bmcgo import misc
from bmcgo.misc import CommandInfo
from bmcgo.utils.tools import Tools
from bmcgo.bmcgo_config import BmcgoConfig

tool = Tools(__name__)
log = tool.log
command_info: CommandInfo = CommandInfo(
    group=misc.GRP_MISC,
    name="sdk_build",
    description=["构建openubmc_sdk"],
    hidden=False,
)


def if_available(bconfig: BmcgoConfig):
    return bconfig.manifest is not None


class BmcgoCommand:
    def __init__(self, bconfig: BmcgoConfig, *args):
        self.bconfig = bconfig
        parser = argparse.ArgumentParser(
            prog="bingo sdk_build",
            description="构建openubmc_sdk",
            add_help=True,
            formatter_class=argparse.RawTextHelpFormatter,
        )
        parser.add_argument("--user", default="openubmc", help="用户")
        parser.add_argument("--channel", default="stable", help="用户")

        parsed_args, _ = parser.parse_known_args(*args)
        self.user = parsed_args.user
        self.channel = parsed_args.channel
        self.build_dir = self.bconfig.manifest.folder
        self.version = ""

    def run(self):
        build_path = os.path.join(self.build_dir, "build", "sdk")
        if not os.path.exists(build_path):
            log.warning("当前manifest下不存在sdk文件夹，取消openubmc_sdk构建")
            return
        os.chdir(build_path)
        manifest_path = os.path.join(build_path, "manifest.yml")
        with open(manifest_path, "r") as yaml_fp:
            obj = yaml.safe_load(yaml_fp)
        self.version = obj["base"]["version"]
        tool.run_command(
            f"conan create . --version={self.version} --user={self.user} --channel={self.channel}",
            show_log=True,
        )
