#!/usr/bin/env python
# coding: 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 sys
import shutil
import logging
import platform
import subprocess
import tempfile
import stat
import argparse

from bmcgo import __version__

cwd = os.getcwd()
BINGO_SRC_DIR = "bmcgo"


class Build(object):
    def __init__(self, args):
        self.output_dir = os.path.join(cwd, "output")
        self.package_name = args.package_name
        if os.path.isdir(self.output_dir):
            shutil.rmtree(self.output_dir)
        os.makedirs(self.output_dir)

    def run_command(self, command, check=True):
        """
        如果ignore_error为False，命令返回码非0时则打印堆栈和日志并触发异常，中断构建
        """
        logging.info("执行命令: (%s)", " ".join(command))
        subprocess.run(command, check=check)

    def package_pip(self):
        """
        构建bmcgo工具的pip包
        """
        setup_file = "setup.py"
        tmp_dir = tempfile.TemporaryDirectory()
        build_dir = os.path.join(tmp_dir.name, BINGO_SRC_DIR)
        shutil.copytree(BINGO_SRC_DIR, build_dir)
        shutil.copyfile(setup_file, os.path.join(tmp_dir.name, setup_file))
        shutil.copyfile("MANIFEST.in", os.path.join(tmp_dir.name, "MANIFEST.in"))
        if os.path.isdir("dist"):
            shutil.rmtree("dist")
        os.chdir(tmp_dir.name)
        cmd = ["/usr/bin/python3", setup_file, "bdist_wheel"]
        self.run_command(cmd)
        file_name = self.package_name.replace("-", "_")
        cmd = ["/usr/bin/cp", f"dist/{file_name}-{__version__}-py3-none-any.whl", self.output_dir]
        self.run_command(cmd)
        os.chdir(cwd)

    def package_deb(self):
        """
        打包deb包
        """
        logging.info("开始打 deb 包")
        tmp_dir = tempfile.TemporaryDirectory()
        deb_dir = os.path.join(tmp_dir.name, "deb")
        shutil.copytree(os.path.join(cwd, "tools", "deb"), deb_dir)

        control = os.path.join(deb_dir, "DEBIAN/control")
        cmd = ["/usr/bin/sed", "-i", f"s@<version>@{__version__}@g", control]
        self.run_command(cmd)

        mach = platform.machine()
        dst = os.path.join(cwd, f"output/openubmc_bingo_{mach}.deb")
        self.run_command(["/usr/bin/dpkg", "-b", deb_dir, dst])

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="build package", formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("--package_name", help="package name", default='openubmc-bingo')
    args = parser.parse_args()
    b = Build(args)
    b.package_pip()
    b.package_deb()
