#!/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 glob
import json
import os
import stat
import subprocess


# 定制化脚本，由manifest构建时调用
class Customization():
    def __init__(self, board_name, rootfs_path):
        self.board_name = board_name
        self.rootfs_path = rootfs_path

    def post_image(self):
        pass

    def post_rootfs(self):
        if os.path.exists(f'{self.rootfs_path}/usr/bin/clp_commands'):
            subprocess.run(['/usr/bin/sudo', '/usr/sbin/setcap', 'cap_setuid+eip',
                f'{self.rootfs_path}/usr/bin/clp_commands'], check=True)

        # 增加busybox.suid文件的s权限
        subprocess.run(['/usr/bin/sudo', '/usr/bin/chmod', '+s', f'{self.rootfs_path}/bin/busybox.suid'], check=True)
        # 删除空链接文件
        files_to_delete = [
            "/bin/chattr.e2fsprogs",
            "/etc/systemd/system/multi-user.target.wants/sshd@.service",
            "/lib/systemd/system/sysinit.target.wants/systemd-hwdb-update.service",
            "/sbin/mke2fs.e2fsprogs",
            "/usr/share/terminfo/a/ansi",
            "/usr/share/terminfo/r/rxvt",
            "/usr/share/terminfo/s/screen-256color",
            "/usr/share/terminfo/s/sun",
            "/usr/share/terminfo/v/vt100",
            "/usr/share/terminfo/v/vt102",
            "/usr/share/terminfo/v/vt220",
            "/usr/share/terminfo/v/vt52",
            "/usr/share/terminfo/x/xterm-256color",
            "/usr/share/terminfo/x/xterm-color",
            "/usr/share/terminfo/x/xterm-xfree86",
            # 删除冗余二进制文件 - /usr/bin/
            "/usr/bin/passwd",
            # 删除冗余二进制文件 - /usr/sbin/
            "/usr/sbin/useradd",
            "/usr/sbin/usermod",
            "/usr/sbin/userdel",
            "/usr/sbin/newusers",
            "/usr/sbin/groupmod",
            "/usr/sbin/groupadd",
            "/usr/sbin/groupdel",
            "/usr/sbin/groupmems",
            "/usr/sbin/grpck",
            "/usr/sbin/grpconv",
            "/usr/sbin/grpunconv"
        ]
        for file in files_to_delete:
            subprocess.run(['/usr/bin/sudo', '/usr/bin/rm', '-rf', f'{self.rootfs_path}' + file], check=True)

        with open(os.path.join(os.path.dirname(__file__), "permission.json")) as file_descriptor:
            content = json.load(file_descriptor)

        for item, perm in content:
            for entry in glob.glob(f'{self.rootfs_path}{item}'):
                realpath = self.get_realpath(entry)
                if not os.path.exists(realpath):
                    continue
                if oct(os.stat(realpath)[stat.ST_MODE])[-3:] <= perm:
                    continue
                subprocess.run(['/usr/bin/sudo', '/usr/bin/chmod', perm, realpath], check=True)

    def get_realpath(self, entry):
        if os.path.islink(entry):
            link = os.readlink(entry)
            if link.startswith('/'):
                return f'{self.rootfs_path}{link}'
            return os.path.join(os.path.dirname(entry), link)
        return entry