#!/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 stat
import shutil
import pathlib

from bmcgo import errors
from bmcgo.tasks.task import Task
from bmcgo.utils.config import Config


class TaskClass(Task):
    def __init__(self, config: Config, work_name=""):
        super().__init__(config, work_name)
        self.luajit_pkg = self.get_com_pkg()

    def get_com_pkg(self):
        com_list = self.config.get_subsys_coms()
        luajit_pkg = [com for com in com_list if com.startswith("luajit")]
        if len(luajit_pkg) < 1:
            raise errors.BmcGoException("subsys 中未定义luajit组件版本号，请检查后再执行!")
        return luajit_pkg[0]
        
    def install_luac(self):
        
        conan_bin = os.path.join(os.path.expanduser('~'), ".conan", "bin")
        if not os.path.isdir(conan_bin):
            os.makedirs(conan_bin)

        ld_library_path = conan_bin + ":" + os.environ.get("LD_LIBRARY_PATH", "")
        os.environ["LD_LIBRARY_PATH"] = ld_library_path
        path = conan_bin + ":" + os.environ.get("PATH", "")
        os.environ["PATH"] = path
        os.environ["LUA_PATH"] = f"{conan_bin}/?.lua"

        luajit_flag = self.luajit_pkg.split("@")[0].replace("/", "_")
        luajit_flag = os.path.join(conan_bin, luajit_flag)

        luac_path = os.path.join(conan_bin, "luajit")
        if os.path.isfile(luajit_flag) and os.path.exists(luac_path):
            os.chmod(luac_path, stat.S_IRWXU)
            return
        if os.path.isdir(conan_bin):
            for file in os.listdir(conan_bin):
                file_path = os.path.join(conan_bin, file)
                if os.path.isfile(file_path):
                    os.remove(file_path)
        else:
            os.makedirs(conan_bin)
        append_cmd = f"-r openubmc_dev"
        self.run_command(f"conan install {self.luajit_pkg} {append_cmd}" +
                            " -pr profile.dt.ini -if=temp/.deploy -g deploy")
        cmd = f"cp temp/.deploy/luajit/usr/bin/luajit {conan_bin}"
        self.run_command(cmd)
        cmd = f"cp temp/.deploy/luajit/usr/lib64/liblua.so {conan_bin}"
        self.run_command(cmd)
        cmd = f"cp -r temp/.deploy/luajit/usr/bin/jit {conan_bin}"
        self.run_command(cmd)
        os.chmod(luac_path, stat.S_IRWXU)
        luajit2luac = shutil.which("luajit2luac.sh")
        cmd = f"cp {luajit2luac} {conan_bin}/luac"
        self.run_command(cmd)
        pathlib.Path(luajit_flag).touch(0o600, exist_ok=True)

    def run(self):
        return
