#!/bin/bash

if [ "x$(id -u)" != "x0" ] ; then
	echo "You must run this as root"
	exit 1
fi

kysec_conf=/etc/kysec/kysec.conf
if [ ! -f /etc/kysec/kysec.conf ]; then
	kysec_conf=/etc/kylin-security.conf
fi

echo "开启UID唯一性检查"
if [ -n "$(grep "state=off" /etc/chkuid_state)" ]; then
	sed -i 's/state=off/state=on/g' /etc/chkuid_state
fi

echo "开启审计"
if [ -n "$(grep "audit=0" /etc/default/grub)" ]; then
	sed -i 's/audit=0//g' /etc/default/grub
	# 下面在执行security-switch时会执行update-grub，
	# 且ksc-set依赖的security-switch的default状态是开启审计的
	# update-grub >/dev/null 2>&1
fi

# 先设置为default状态，通用版本执行 security-switch --set default 之后的
# 配置就是默认的安全状态（/usr/share/libsecurity-conf/data/kysec.conf）
echo "设置默认安全状态"
/usr/sbin/security-switch --set default >/dev/null 2>&1

#sed -i 's/kysec_status =.*/kysec_status = 2/' "$kysec_conf"
#sed -i 's/kysec_exectl =.*/kysec_exectl = 2/' "$kysec_conf"
#sed -i 's/kysec_netctl =.*/kysec_netctl = 2/' "$kysec_conf"
#sed -i 's/kysec_ppro =.*/kysec_ppro = 1/' "$kysec_conf"
#sed -i 's/kysec_3adm =.*/kysec_3adm = 0/' "$kysec_conf"

# 重新初始化白名单
# echo "需要重新初始化白名单"
# sqlite3 /etc/kysec/db/whlist.db 'update relabel_status set relabel=0';
[ ! -e /.exectl ] && touch /.exectl

# 防火墙设置为办公网络
#echo "防火墙设置为办公网络"
#sed -i 's/Zone=.*/Zone=work/' /etc/kylin-firewall/kylin-firewall.conf
sed -i 's/Mode=.*/Mode=all/' /etc/kylin-firewall/kylin-firewall.conf
[ -n "$(dpkg-query -l | grep ufw)" ] && ufw disable

# dpkg警告弹框
if [ -n "$(dpkg-query -l | grep libkylin-signtool)" ]; then
	sed -i 's/.*allow-kylinsign.*/allow-kylinsign/g' /etc/dpkg/dpkg.cfg
	sed -i 's/.*verify-kylinsign.*/verify-kylinsign/g' /etc/dpkg/dpkg.cfg
fi

#设备管控
echo "对内置设备进行授权"
/usr/sbin/ksc-dinit 2>/dev/null || true
echo "授权完成"

#招行、港澳专版的特殊处理
check_support_hkmm="/usr/bin/check-support-hkmm"
if [ -f /etc/.support-tpm ]; then
	cryptsetup tpmSuspendUpdateFirst
elif [ -x "$check_support_hkmm" ]; then
	if /usr/bin/check-support-hkmm; then
		cryptsetup tpmSuspendUpdateFirst
	fi
fi

#可信度量
spi_sysconfig_file="/usr/sbin/spi_sysconfig"
if [ -x "$spi_sysconfig_file" ]; then
  echo "关闭可信度量"
  /usr/sbin/spi_sysconfig -a write -i measuremode -m stop 2>/dev/null || true
  echo "已关闭"
fi

#bug214277 蒙文繁文磁盘加密登录界面未翻译
dpkg-reconfigure  cryptsetup-initramfs

echo "安全状态设置完成，请重启系统"
