# 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.
from conanbase import ConanBase, copy, os


required_conan_version = ">=1.60.0"


def build_ldap_enabled_configure():
    configure = ""
    with open('src/model/configure.ts', 'r') as fi:
        configure = fi.read()
    configure = configure.replace("export const LDAP_PAGE_ENABLED = true;", "export const LDAP_PAGE_ENABLED = false;")
    with open('src/model/configure.ts', 'w') as fo:
        fo.write(configure)


def build_energy_enabled_configure():
    configure = ""
    with open('src/model/configure.ts', 'r') as fi:
        configure = fi.read()
    configure = configure.replace("export const ENERGY_PAGE_ENABLED = true;", 
                                    "export const ENERGY_PAGE_ENABLED = false;")
    with open('src/model/configure.ts', 'w') as fo:
        fo.write(configure)


class WebUIConan(ConanBase):
    name = "webui"
    license = "BSD licence"
    generators = "VirtualBuildEnv"
    homepage = "https://www.huawei.com/"
    description = ""
    chost = None
    settings = "arch"

    def build(self):
        ldap_enabled = self.options.ldap_enabled
        energy_enabled = self.options.energy_enabled
        if ldap_enabled == False:
            build_ldap_enabled_configure()
        if energy_enabled == False:
            build_energy_enabled_configure()
        self.run(f"npm install")
        self.run(f"npm run build")

    def package(self):
        self.run(f"rm -rf node_modules")
        self.run(f"npm install --production")
        if os.path.isfile("public/permissions.ini"):
            copy(self, "permissions.ini", src=os.path.join(self.source_folder, "public"), 
                dst=self.package_folder, keep_path=True)
        # 切换dist为工作目录
        copy(self, "*", src=os.path.join(self.source_folder, "dist"), 
            dst=os.path.join(self.package_folder, "opt/bmc/web/htdocs/"))
    
    def layout(self):
        pass
