#!/bin/bash

set -e
#PREREQ="framebuffer console_setup"
PREREQ="system-layer"

prereqs () {
	echo "$PREREQ"
}

case $1 in
	prereqs)
		prereqs
		exit 0
		;;
esac

. /scripts/functions
. /scripts/security-functions

selinux_enable=0
check_selinux_param(){
        # check security or lsm  include selinux param
        if grep -Eq '(^| )(lsm|security)=[^ ]*selinux' /proc/cmdline ;then
                # check selinux=0 is exists
                if ! grep -Eq '(^| )selinux=0(\s|$)' /proc/cmdline ;then
                        selinux_enable=1
                fi
        fi

}

check_selinux_param
if [ ${selinux_enable} -eq 0 ];then
        exit 0
fi

#set -x
mount -o remount,rw ${ROOT} ${rootmnt}

# Mount the selinux directory in both the ramdisk's root as well as in
# the real root directory.
mkdir -p /selinux

# Temporarily pivot to the real root directory, loading the policy
# from that disk.  Normally this process will occur by init, but kinit
# is not compiled against libselinux.  Therefore use load_policy to
# perform the same initialization.
set +e

clear


mount_backup_partition() {
        if [ -f $rootmnt/etc/.bootinfo ]; then
                . $rootmnt/etc/.bootinfo
                if [ $SNAPSHOT_ENABLED -eq 1 ]; then
                    if [ -e $rootmnt/dev/disk/by-uuid/$RECOVERY_DEV_UUID ]; then
                        mount -t ext4 $rootmnt/dev/disk/by-uuid/$RECOVERY_DEV_UUID $rootmnt/backup
                    fi
                fi
        fi     
}

umount_backup_partition() {
        if [ -f $rootmnt/etc/.bootinfo ]; then
                . $rootmnt/etc/.bootinfo
                if [ $SNAPSHOT_ENABLED -eq 1 ]; then
                        umount $rootmnt/backup 
                fi
        fi     
}

#relabel#
statusfile=${rootmnt}/etc/selinux/.autorelabel

# Get the selinux configuration variables
SELINUXTYPE=""
if [ -e ${rootmnt}/etc/selinux/config ]; then
	. ${rootmnt}/etc/selinux/config
fi

if [ "x${SELINUXTYPE}" = "x" ]; then
	log_failure_msg "No SELinux policy found"
	exit 0
elif [ ! -d ${rootmnt}/etc/selinux/${SELINUXTYPE} ]; then
	log_failure_msg "No SELinux policy found"
	exit 0
elif [ ! -e ${rootmnt}/etc/selinux/${SELINUXTYPE}/policy/policy.33 ]; then
	log_failure_msg "No SELinux policy found"
	exit 0
fi

#change system exectl mode to softmode
securityfs_mnt=/sys/kernel/security
kysec_status_path="$securityfs_mnt/ksaf/status"

kysec_is_enabled(){
        if [ -e "$kysec_status_path" ]; then
                cat "$kysec_status_path"
        else
                echo 0
        fi
}

kysec_enabled=`kysec_is_enabled`

set_kysec_status(){
        echo $1 > $kysec_status_path
}

#check whether cmdline selinux autorelabel
export autorelabel=

for x in $(cat /proc/cmdline); do
       	case $x in
       	autorelabel)
               	autorelabel=y
       	        ;;
        esac
done

#if [ ! -e $statusfile -a  "x${autorelabel}" = "x" ]; then
#	exit 0
#fi

mount -t sysfs -o nodev,noexec,nosuid sysfs ${rootmnt}/sys
mount -t proc -o nodev,noexec,nosuid proc ${rootmnt}/proc
mount -t devtmpfs udev "$rootmnt/dev"

mount -t securityfs | grep -q "securityfs"
if [ $? -ne 0 ]; then
	mount -t securityfs -o nodev,noexec,nosuid none ${rootmnt}/sys/kernel/security/
fi

chroot ${rootmnt} /sbin/load_policy -i
RET=$?

mount -t selinuxfs none /selinux || \
    log_warning_msg "Unable to mount /selinux"

if [ $RET -eq 3 ]; then
    log_warning_msg "SELinux policy load failed"
elif [ $RET -ne 0 ]; then
    log_warning_msg "SELinux policy load failed, continuing"
else
    log_success_msg "SELinux policy was loaded"
fi



### 配置文件
# - 不可变配置信息文件
#系统overlay配置文件路径
OVERLAY_CONF="/root/sysroot/ostree/pkgs/system-ovl.conf"

# 底层ksaf开关配置文件
ksaf_conf_file=${rootmnt}/etc/ksaf/mod_conf/ksaf_main.conf

# 表示当前系统所处的模式：
#   - maintain[M]：运维模式
#   - normal[N]：用户模式
overlay_mod_conf=N
ksaf_status=0 
if [ -e "$ksaf_conf_file" ]; then
        ksaf_status=$(cat "$ksaf_conf_file")
fi

# 从 OVERLAY_CONF 中获取
path_pre=
stage_initrd=
deploy=

#usr的overlay各路径
Usr_LowerDir=
Usr_UpperDir=
Usr_WorkDir=
Usr_MergeDir=

# arch
machine=`uname -m`

get_mode_conf()
{
    mode=$(grep '^Mode=' "$OVERLAY_CONF" | awk -F'=' '{print $2}')
    if [ "$mode" = "maintain" ];then
        overlay_mod_conf=M
    fi
}

# 函数：替换占位符
replace_placeholders()
{
    local input="$1"
    input="${input//<PathPre>/$path_pre}"
    input="${input//<stage>/$stage_initrd}"
    input="${input//<Deploy>/$deploy}"
    echo "$input"
}

get_preparation_value()
{
	# 提取StageInitrd的值
    stage_initrd=$(awk -F'=' '/^StageInitrd=/ {print $2}' "$OVERLAY_CONF")

    # 提取Deploy的值
    deploy=$(awk -F'=' '/^Deploy=/ {print $2}' "$OVERLAY_CONF")

    # 提取PathPre的值
    path_pre=$(awk -F'=' '/^PathPre=/ {print $2}' "$OVERLAY_CONF")
    path_pre=$(replace_placeholders "$path_pre")
}

get_usr_dir()
{
	get_preparation_value

    in_usr=false
    while IFS= read -r line; do
        if [ "$line" = "[usr-$overlay_mod_conf]" ]; then
            in_usr=true
        elif [ "${line:0:1}" = "[" ] && [ $in_usr ]; then
            in_usr=false
        fi

        if $in_usr; then
            case "$line" in
                *LowerDir=*)
                    Usr_LowerDir=$(replace_placeholders "${line#*LowerDir=}")
                    ;;
                *UpperDir=*)
                    Usr_UpperDir=$(replace_placeholders "${line#*UpperDir=}")
                    ;;
                *WorkDir=*)
                    Usr_WorkDir=$(replace_placeholders "${line#*WorkDir=}")
                    ;;
                *MergeDir=*)
                    Usr_MergeDir=$(replace_placeholders "${line#*MergeDir=}")
                    ;;
                *)
                    ;;
            esac
        fi
    done < "$OVERLAY_CONF"
}


prompt="
Relabeling The SELinux Policy context :
********************************************************
* If you are not already running SELinux, then you can *
* safely ignore the following error message.           *
* SELinux ${SELINUXTYPE} policy relabel is required.   *
* Relabeling could take a very long time, depending    *
* on file system size and speed of hard drives.	       *
********************************************************
* Relabeling files >>>>>>>>"

. ${rootmnt}/etc/default/locale

translate_message()
{
       case "$LANG" in
               zh_CN.*)
                       echo "$1"
               ;;
               en_US.*)
                       echo "$2"
               ;;
               bo_CN.*)
                       echo "$3"
               ;;
	       zh_HK.*)
                       echo "$4"
	       ;;
	       mn_MN.*)
                       echo "$5"
               ;;
               *)
                       echo "$2"
               ;;
       esac
}

# 处理overlay目录与系统目录的映射关系
handle_overlay_dir(){
	get_preparation_value

	local overlay_deploy_dir="/sysroot/ostree/deploy/kylin/deploy/${deploy}"
	local ukmcs_config_path="/etc/selinux/ukmcs/contexts/files/file_contexts.subs_dist"
	local ukmls_config_path="/etc/selinux/ukmls/contexts/files/file_contexts.subs_dist"
	local targeted_config_path="/etc/selinux/targeted/contexts/files/file_contexts.subs_dist"

	# 映射deploy目录为/
	for config_path in `echo ${ukmcs_config_path} ${ukmls_config_path} ${targeted_config_path}`
	do
		if ! grep -q ${overlay_deploy_dir} "${rootmnt}${config_path}" ;then
			echo "${overlay_deploy_dir} /" >> "${rootmnt}${config_path}"
		fi
	done

	# 映射overly目录与系统目录关系
	#	- /sysroot/ostree/pkgs/ovl-${deploy}/etc-vol/etc-[lower|upper|tmpupper|work] --- /etc
	# 	- /sysroot/ostree/pkgs/ovl-${deploy}/usr-vol/usr-[lower|upper|tmpupper|work] --- /usr
	# 	- /sysroot/ostree/pkgs/ovl-${deploy}/var-vol/var-[lower|upper|tmpupper|work] --- /var

	local root_overlay_path_pre=$(echo "${path_pre#${stage_initrd}}")
	local overlay_dirs="etc usr var"
	local overlay_layers="lower upper tmpupper work"
	for dir in `echo ${overlay_dirs}`
	do
	        for layer in `echo ${overlay_layers}`
	        do
	                local overlay_path="${root_overlay_path_pre}/${dir}-ovl/${dir}-${layer}"
			local map_path="${overlay_path} /${dir}"
	                if ! grep -q "${overlay_path}" "${rootmnt}${ukmcs_config_path}" ;then
	                        echo "${map_path}" >> ${rootmnt}${ukmcs_config_path}
	                fi

	                if ! grep -q ${overlay_path} "${rootmnt}${ukmls_config_path}" ;then
	                        echo "${map_path}" >> ${rootmnt}${ukmls_config_path}
	                fi

	                if ! grep -q ${overlay_path} "${rootmnt}${targeted_config_path}" ;then
	                        echo "${map_path}" >> ${rootmnt}${targeted_config_path}
	                fi
	        done
	done
}



if [ $RET -eq 0 ]; then
	if [ -e $statusfile -o  "x${autorelabel}" = "xy" ]; then
		killall plymouthd

		# 设置overlay目录与系统目录的映射关系 解决overlay目录标记不正常问题
		handle_overlay_dir
		# get mode 
		get_mode_conf
		get_usr_dir

		#把/usr的overlay叠加去掉
		umount "$rootmnt/usr"
		#挂载/usr目录可读写
		mount -o remount,rw "$rootmnt/usr"
		mount -o remount,rw "$rootmnt/sysroot"

		/usr/sbin/plymouthd --mode=boot --attach-to-session --pid-file=/run/plymouth/pid
		/usr/bin/plymouth --show-splash

		# 处理/home目录与/data目录bind关系
		DATA_DEVICE=$(awk -F'[[:space:]]+' '$1 ~ /^UUID=/ && $2 == "/data" {print $1}' "$rootmnt/etc/fstab")
		chroot "${rootmnt}" /bin/bash -c "mount $DATA_DEVICE /data"
		mount --bind $rootmnt/data/home $rootmnt/home

		echo "$prompt"
		zh_CN_msg="正在初始化强制访问控制标记，请稍后 ..."
		en_CN_msg="Initializing Mandatory access control token, please wait ......"
		bo_CN_msg="ཐོག་མར་འགྱུར་བཞིན་ཡོད་།བཙན་ཤེད་ཀྱིས་འཚམས་འདྲི་ཚོད་འཛིན་བཀོད་རྟགས་དང་།ཅུང་ཙམ་འགོར་རྗེས་རོགས་། "
		zh_HK_msg="正在初始化強制存取控制標記，請稍後…"
		mn_MN_msg="ᠶᠠᠭ ᠠᠯᠪᠠᠳᠠᠯᠭ᠎ᠠ ᠪᠠᠷ ᠰᠤᠷᠪᠤᠯᠵᠢᠯᠠᠬᠤ ᠡᠵᠡᠮᠰᠢᠯ ᠤᠨ ᠲᠡᠮᠳᠡᠭ ᠢ ᠠᠩᠬᠠᠵᠢᠭᠤᠯᠵᠤ ᠪᠠᠶᠢᠨ᠎ᠠ ᠤᠳᠠᠰᠬᠢᠭᠡᠳ"
		msg="$(translate_message "$zh_CN_msg" "$en_CN_msg" "$bo_CN_msg" "$zh_HK_msg" "$mn_MN_msg")"
		show_message "$msg"

		# 临时将kysec设置为软模式
		if [ "$kysec_enabled" -ne 0 ]; then
			set_kysec_status 4
		fi

		# 临时将selinux设置为软模式
		se_status=`cat /selinux/enforce`
		if [ $se_status -ne 0 ]; then
			echo "0" > /selinux/enforce
		fi

		# 挂载分区
		chroot ${rootmnt} /bin/mount -a
		# 处理/boot/efi分区为只读的情况
		bootpart=$(mount | grep "/boot")
		booteif=$(mount | grep "boot/efi")
		if [ -n "$bootpart" ]; then
			chroot ${rootmnt} mount -o remount,rw /boot
		fi
		if [ -n "booteif" ]; then
			chroot ${rootmnt} mount -o remount,rw /boot/efi
		fi
		mount_backup_partition

		# 记录 / 和 path_pre 是否原本具有 i 属性
		rootmnt_had_i=false
		if chroot "${rootmnt}" lsattr -d / 2>/dev/null | awk '{print $1}' | grep -q 'i'; then
			rootmnt_had_i=true
		fi

		path_pre_had_i=false
		rel_path_pre="${path_pre#${rootmnt}}"
		if [ -n "$rel_path_pre" ] && [ "$rel_path_pre" != "/" ]; then
			if chroot "${rootmnt}" lsattr -d "${rel_path_pre}" 2>/dev/null | awk '{print $1}' | grep -q 'i'; then
				path_pre_had_i=true
			fi
		fi

		# 去除不可变属性以便 relabel
		chattr -i "${rootmnt}" 2>/dev/null || true
		chattr -i "${path_pre}" 2>/dev/null || true

		# 1. 先处理 ${rootmnt}/sysroot目录 
		#    - /sysroot/var/opt和/var/opt是映射关系 不需要处理
		#    - /sysroot/ostree/deploy/kylin/var/opt和/var/opt是映射关系 不需要处理
		#    - /var/opt/kaiming 开明软件的layers层 实际映射的系统下的文件 所以不需要处理 在2步骤中统一处理
		#    - $root_deploy_path_pre/$deploy 实际是系统的/目录 最后处理
	
		root_deploy_path_pre="/sysroot/ostree/deploy/kylin/deploy"
		chroot ${rootmnt} /sbin/restorecon -RF -e ${root_deploy_path_pre} -e /sysroot/var/opt -e /sysroot/ostree/deploy/kylin/var/opt /sysroot >/dev/null 2>&1
		chroot ${rootmnt} /sbin/restorecon -RF ${root_deploy_path_pre}/${deploy}/var/opt/kaiming >/dev/null 2>&1
		chroot ${rootmnt} /sbin/restorecon -RF -e ${root_deploy_path_pre}/${deploy}/var/opt/kaiming ${root_deploy_path_pre}/${deploy} >/dev/null 2>&1

		# 2. /sysroot/ostree/deploy/kylin/deploy下的目录和rootmnt目录是硬链接关系,
		# 前面已经处理过/sysroot 所以不需要处理了
		# 需要单独处理/var/opt
		chroot ${rootmnt} /sbin/restorecon -RF   /var/opt >/dev/null 2>&1
		chroot ${rootmnt} /sbin/restorecon -RF  -e /sysroot -e /var/opt / >/dev/null 2>&1


		# 由于递归设置/标记时 不能确定是/home 还是/data/home 被标记的先后顺序(如果/data/home后标记,用户家目录标记会不正确)
		# 这里需要将用户家目录数据重新恢复标记
		chroot ${rootmnt} /sbin/restorecon -RF /home >/dev/null  2>&1
		chroot ${rootmnt} /sbin/restorecon -RF /root >/dev/null  2>&1
		umount_backup_partition
		log_end_msg $?
		/bin/rm -f $statusfile

		# 3. 当手动关闭过selinux后(grub去除掉selinux参数 或者selinux=0) 会自动创建/.autorelabel文件(开源默认动作)
		# 该文件会触发systemd时 selinux-autorelabel服务
		# 我们这里自己打标机了 就不需要开源的selinux-autorelabel服务重新打标机了
		[ -e "${rootmnt}/.autorelabel" ] && /bin/rm -f "${rootmnt}/.autorelabel"

		mount -o rw,bind,remount "/tmproot" "$rootmnt/sysroot"
		#挂载/usr目录只读
		mount -o ro,bind,remount "$rootmnt/usr" "$rootmnt/usr"
		mount -o rw,bind,remount "/tmproot" "$rootmnt/sysroot"
		if [ "x$machine" != "xsw_64" ]; then
			#加载/usr的overlay叠加
			if [ "${overlay_mod_conf}" = "N" ]; then
				mount -t overlay overlay -o lowerdir=${Usr_LowerDir},workdir=${Usr_WorkDir} ${Usr_MergeDir}
			else
				mount -t overlay overlay -o lowerdir=${Usr_LowerDir},upperdir=${Usr_UpperDir},workdir=${Usr_WorkDir} ${Usr_MergeDir}
			fi
		else
			#加载/usr的overlay叠加
			if [ "${overlay_mod_conf}" = "N" ]; then
				mount -t overlay overlay -o lowerdir=${Usr_LowerDir},workdir=${Usr_WorkDir},index=off ${Usr_MergeDir}
			else
				mount -t overlay overlay -o lowerdir=${Usr_LowerDir},upperdir=${Usr_UpperDir},workdir=${Usr_WorkDir},index=off ${Usr_MergeDir}
			fi
		fi
		$rootmnt_had_i && chattr +i "${rootmnt}" 2>/dev/null || true
		$path_pre_had_i && chattr +i "${path_pre}" 2>/dev/null || true

		# 恢复kysec 和 selinux 默认状态
		set_kysec_status ${ksaf_status}
		echo $se_status > /selinux/enforce

		#clear_message
	fi
fi
#relabel end#
umount ${rootmnt}/proc
umount ${rootmnt}/sys/fs/selinux
umount ${rootmnt}/sys
umount $rootmnt/dev
clear
