# 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 subprocess


# 定制化脚本，由manifest构建时调用
class Customization(object):

    def __init__(self, board_name, rootfs_path):
        self.board_name = board_name
        self.rootfs_path = rootfs_path

    def post_image(self):
        subprocess.run(['/usr/bin/sudo', '/usr/bin/ln', '-sf',
                        '/data/trust/passwd', f'{self.rootfs_path}/etc/passwd'], check=True)
        subprocess.run(['/usr/bin/sudo', '/usr/bin/ln', '-sf',
                        '/data/trust/shadow', f'{self.rootfs_path}/etc/shadow'], check=True)
        subprocess.run(['/usr/bin/sudo', '/usr/bin/ln', '-sf',
                        '/data/trust/group', f'{self.rootfs_path}/etc/group'], check=True)

    def post_rootfs(self):
        subprocess.run(['/usr/bin/sudo', '/usr/bin/sed', '-i', '$ a dir = /dev/shm/tallylog',
                        f'{self.rootfs_path}/etc/security/faillock.conf'], check=True) 
        subprocess.run(['/usr/bin/sudo', '/usr/bin/sed', '-i',
                        '/session       required   pam_env.so readenv=1/a auth  include /data/trust/pam_faillock\\\n' +
                        'auth       required   pam_bmc_login.so',
                        f'{self.rootfs_path}/etc/pam.d/login'], check=True)
        subprocess.run(['/usr/bin/sudo', '/usr/bin/sed', '-i',
                        '/account    include      common-account/a account    required     pam_bmc_login.so',
                        f'{self.rootfs_path}/etc/pam.d/login'], check=True)
        subprocess.run(['/usr/bin/sudo', '/usr/bin/sed', '-i',
                        '/auth       include      common-auth/a auth       required     pam_bmc_login.so',
                        f'{self.rootfs_path}/etc/pam.d/sshd'], check=True)
        # 过滤域用户(uid>=1000)环境变量USER/LOGNAME赋值uid
        user_insert1 = 'if [ `id -u` -lt 1000 ]; then'
        user_insert2 = 'fi'
        subprocess.run(['/usr/bin/sudo', '/usr/bin/sed', '-i', f'/^USER=/i {user_insert1}',
            f'{self.rootfs_path}/etc/profile'], check=True)
        subprocess.run(['/usr/bin/sudo', '/usr/bin/sed', '-i', f'/^LOGNAME=\$USER/a {user_insert2}',
            f'{self.rootfs_path}/etc/profile'], check=True)