#!/bin/bash

jyn_install_path=$(cd `dirname $0`;pwd)
udisk_flag=0

ins_info_dir="$jyn_install_path/insinfo"
jyoem="${ins_info_dir}/jyoem"
ccip="${ins_info_dir}/ccip"
domain_path="${ins_info_dir}/jydomain"
nostart_path="${ins_info_dir}/jynostart"
rs_path="${ins_info_dir}/rspath"
soft_name=${jyn_install_path%/}
soft_name=${soft_name##*/}
desktop_name="${soft_name}.desktop"

is_ui()
{
	CTYPE_VALUE=`cat $jyn_install_path/Config/Version.ini|grep -v "Mon"|grep -v "Version"|grep "Type"`
    if [ ${CTYPE_VALUE:10:1} == "1" ];then
        echo "1"
    fi
}

is_sdk()
{
	CTYPE_VALUE=`cat $jyn_install_path/Config/Version.ini|grep -v "Mon"|grep -v "Version"|grep "Type"`
    if [ ${CTYPE_VALUE:18:1} == "4" ];then
        echo "1"
    fi
}

is_service()
{
	VTYPE_VALUE=`cat $jyn_install_path/Config/Version.ini|grep "VersionType"`
    if [[ ${VTYPE_VALUE} =~ "service" ]];then
        echo "1"
    fi
}

#涉密
is_sm()
{
	smUi=`grep "ZYJ = " $jyn_install_path/Config/Version.ini | awk '{print $3}' | tr -d "\n"`
	if [ -n "${smUi}" ] ; then
		echo "1"
	fi
}

set_ip_or_domain()
{
	echo setup_time=`date +%s` >> $jyn_install_path/JingyunUiConfig.ini
	if [ -f $ccip ]; then
		ip=`cat $ccip`
		if [ "$ip" != "" ]; then
			sed -i "/^Url.1/cUrl.1=http://$ip" $jyn_install_path/Config/UrlService.ini
			sed -i "/^ServiceUrl.10/cServiceUrl.10=http://$ip[tcp:3006]" $jyn_install_path/Config/UrlService.ini
		fi	
	fi
	
	if [ -f $domain_path ]; then
		domain=`cat $domain_path`
		if [ "$domain" != "" ]; then
			sed -i "/^Url.1/cUrl.1=http://$domain" $jyn_install_path/Config/UrlService.ini
			sed -i "/^ServiceUrl.10/cServiceUrl.10=http://$domain[tcp:3006]" $jyn_install_path/Config/UrlService.ini
		fi
	fi 
}

check_local_version(){
    if [ -f /etc/issue ] ;then
        local_version=$(cat /etc/issue | grep "Ubuntu 14.04.5")
        if [ "$local_version"e != ""e ]; then
            echo $local_version
            UdiskScan=$(cat $jyn_install_path/UiConfig.ini | grep "UdiskScan")
            if [ "$UdiskScan"e != ""e ]; then
                sed -i "/^Udisk/cUdiskScan = 0" $jyn_install_path/UiConfig.ini
            else 
                echo "UdiskScan = 0" >> $jyn_install_path/UiConfig.ini
            fi
        fi
        # 自Ubuntu 20.04开始，桌面快捷方式加白由yes变为true
        local_version=`cat /etc/issue | head -n1 | cut -b 1-12`
        if [[ "${local_version}" > "Ubuntu 20.03" ]];then
            sudo -u $curuser -E gio set $desktop_path/JYNRJJH2.desktop metadata::trusted true
            echo $desktop_path/JYNRJJH2.desktop >> $jyn_install_path/insinfo/desktop_path
        fi
    fi
}

command_exists(){
	command -v "$1" &> /dev/null;
}

restore(){
	if test -e $1".old"; then
        cp $1".old" $1
		rm $1".old"
    fi
}

set_xdg_runtime_dir()
{
    username=`$jyn_install_path/cur_user`
    #uid=`runuser -l $username -c 'echo $UID'`      
    uid=`getent passwd $username|awk -F : '{print $3}'`
    if [ -z $XDG_RUNTIME_DIR ] ;then
        export XDG_RUNTIME_DIR=/run/user/$uid
    fi
    echo $XDG_RUNTIME_DIR
}

copy_scan_menu()
{
	lib_menu_suport_list="caja nautilus peony"
	#file support: nemo , dde-filemanager

	for each in $lib_menu_suport_list
	do
		if command_exists $each ; then
			check_pack="$each $each-open-terminal"
			extensions="extensions-"
			if [ "$each"e == "peony"e ] ; then
				extensions="-extensions"
			fi

			if command_exists rpm; then
                lib_target_dir=`rpm -ql $check_pack| grep $extensions | grep .so | head -n 1`
                lib_target_dir=${lib_target_dir%/*}
			elif command_exists dpkg; then
                lib_target_dir=`dpkg -L  $check_pack | grep $extensions | head -n 1`

			fi
			#这一步作为caja nautilus的容错(sm_mips64el_yh),peony经测没有在Elf中写入右键库路径
			if [ "${lib_target_dir}"e = ""e ]; then
					lib_target_dir=`strings /usr/bin/$each | grep usr/lib | grep extensions`
			fi
			#这一步作为peony的容错(欧拉)
			if [[ "${lib_target_dir}"e == ""e && -f /usr/lib64/lib${each}.so.3 ]]; then
			        lib_target_dir=`strings /usr/lib64/lib${each}.so.3 | grep usr/lib | grep extensions`
			fi
                        #peony版本容错
                        lib_target_ver=`strings /usr/lib64/lib${each}.so.3 | grep "3.10.0" | head -1`
                        if [[ "${lib_target_ver}"e != ""e ]]; then
                                if [ -f ${jyn_install_path}/gjyn/$each/libpeony-gjyn.so ] && [ -f ${jyn_install_path}/gjyn/$each/libpeony-gjyn-3.10.0.so ]; then
                                        mv ${jyn_install_path}/gjyn/$each/libpeony-gjyn-3.10.0.so ${jyn_install_path}/gjyn/$each/libpeony-gjyn.so
                                fi
                        fi

            if [ "$lib_target_dir"e != ""e ]; then
                postfix=${lib_target_dir##*/}
                if [[ ! $postfix =~ "extensions" ]]; then
                    lib_target_dir=${lib_target_dir%/*}
                fi
			if [ -d $jyn_install_path/gjyn/$each ]; then
			    rs_lib_name=`ls $jyn_install_path/gjyn/$each/*`
			    rs_lib_name=${rs_lib_name##*/}
			fi
			if [ -f $jyn_install_path/gjyn/$each/$rs_lib_name ]; then
			    echo "copy $each to $lib_target_dir"
				if [ "$(is_sm)"e == "1"e ] ; then
                	ln -f $jyn_install_path/gjyn/$each/$rs_lib_name $lib_target_dir
				else
                	cp $jyn_install_path/gjyn/$each/$rs_lib_name $lib_target_dir
				fi
                echo "$lib_target_dir/$rs_lib_name" > $rs_path
			fi
			return
            fi
		fi
	done

	if command_exists nemo ; then
		echo "copy nemo files"
		if [ "$(is_sm)"e == "1"e ] ; then
			ln -f $jyn_install_path/gjyn/nemo/jynscan.nemo_action /usr/share/nemo/actions/
		else
			cp $jyn_install_path/gjyn/nemo/jynscan.nemo_action /usr/share/nemo/actions/
		fi
		echo "/usr/share/nemo/actions/jynscan.nemo_action" > $rs_path
	elif command_exists dde-file-manager ; then
		echo "cp dde-file-manager files"
		if [ "$(is_sm)"e == "1"e ] ; then
			ln -f $jyn_install_path/gjyn/dde/deepin-vrvsd-tl.desktop  /usr/share/deepin/dde-file-manager/oem-menuextensions/
		else
			cp $jyn_install_path/gjyn/dde/deepin-vrvsd-tl.desktop  /usr/share/deepin/dde-file-manager/oem-menuextensions/
		fi
		echo "/usr/share/deepin/dde-file-manager/oem-menuextensions/deepin-vrvsd-tl.desktop" > $rs_path
	fi
}
#
smui_config(){

	#安装内核模块(涉密界面版才会有)
	KO_PATH=$jyn_install_path/ZDFY001.ko
	if [ -f ${KO_PATH} ] ;then
		insmod $KO_PATH
	else
		return
	fi
	
	#添加涉密界面版本托盘配置
	if [ -e /opt/software/config.ini ];then
		sed -i '/jingyunsd/,+5d' /opt/software/config.ini
		sed -i '/title=病毒防治/,+4d' /opt/software/config.ini

		#smui_config=`cat /opt/software/config.ini`
		my_config="[jingyunsd]\ntitle=病毒防治\ncmd=/opt/BDFZ/JYN/JYNRJJH1\npixmap_path=/opt/BDFZ/JYN/LOGO/jy_logo_blue32.png\npixmap_path_ex=/opt/BDFZ/JYN/LOGO/jy_logo_dark32.png\nstatus=0\n"
		##判断配置是否已存在
		#if [[ ${smui_config} =~ "[jingyunsd]" && ${smui_config} =~ "cmd=/opt/BDFZ/JYN/JYNRJJH" ]]; then
		#	return
		#else
			echo -e ${my_config} >> /opt/software/config.ini
		#fi
        fi
}

start_run(){
	isuos=`cat /etc/issue | grep UOS`
	isopenEuler=`cat /etc/system-release | grep openEuler`
	# if [[ "a$isuos" == "a" && "e$isopenEuler" == "e" ]] ; then
	if [ "a$isuos" == "a" ] ; then
		if [ -f $jyn_install_path/JYNRJJH2 ] ; then
			status=`$jyn_install_path/JYNRJJH2 --checkRunsNormally`
			if [ "x$status" != "xRunNormally" ]; then
				mkdir -p $jyn_install_path/rtl $jyn_install_path/platforminputcontexts $jyn_install_path/platforms $jyn_install_path/xcbglintegrations
				cp -r $jyn_install_path/rtl.b/* $jyn_install_path/rtl
				cp -r $jyn_install_path/platforminputcontexts.b/* $jyn_install_path/platforminputcontexts
				cp -r $jyn_install_path/platforms.b/* $jyn_install_path/platforms
				cp -r $jyn_install_path/xcbglintegrations.b/* $jyn_install_path/xcbglintegrations
				# rm -rf $jyn_install_path/rtl.b $jyn_install_path/platforminputcontexts.b $jyn_install_path/platforms.b $jyn_install_path/xcbglintegrations.b
			fi
		fi
	fi
	#不自动拉起服务
	if [ -f $nostart_path ] && [ "`cat $nostart_path`" != "" ]; then
		return
	fi

	arr_svr_name=(jyngjcz jyngltx jynzdfy jynengsvr jynproc)
	for svr_name in ${arr_svr_name[@]}; do
		if command -v "systemctl" &> /dev/null ; then
			if [ "`systemctl list-unit-files | grep $svr_name.service`" != "" ] ;then
				systemctl stop $svr_name
				systemctl start $svr_name
			fi
		else
			if test -f /etc/init.d/$svr_name ; then
				service $svr_name stop
				service $svr_name start
				service $svr_name status
			fi
		fi
	done

	if [[ $(is_ui) || $(is_service) ]] ; then
		if [ ! $(is_sdk) ] ; then 
			set_xdg_runtime_dir
			if test -f "/tmp/rpminstall.log"; then
				rm -f /tmp/rpminstall.log
			fi
			if [ -f $jyn_install_path/cur_user ]; then
				sudo -u `$jyn_install_path/cur_user | head -1` -H -E $jyn_install_path/JYNRJJH1 >> /tmp/rpminstall.log 2>&1 &
			fi
		fi
	fi
}

cp_config()
{
	virusver=`cat $jyn_install_path/Config.ini|grep VirusVersion`
	restore $jyn_install_path/Config.ini
	sed -i '/InstallVersion/d' $jyn_install_path/Config.ini
	sed -i '/Type/d' $jyn_install_path/Config.ini
	sed -i "/^VirusVersion/c$virusver" $jyn_install_path/Config.ini
	sed -i "/^SelfProtect/cSelfProtect = 1" $jyn_install_path/Config.ini
}

cp_file()
{
	if [ ! -d "$jyn_install_path/RJJHetc" ];then
		mkdir "$jyn_install_path/RJJHetc"
	fi

	if [ ! -d "$jyn_install_path/RJJHetc/PROTECTION_LOG" ];then
		mkdir "$jyn_install_path/RJJHetc/PROTECTION_LOG"
	fi

	if [ ! -d "$jyn_install_path/RJJHetc/ScanResults" ];then
		mkdir "$jyn_install_path/RJJHetc/ScanResults"
	fi

	if test -f $jyn_install_path/scripts/check_cpplib.sh ; then
		mkdir -p $jyn_install_path/rtl
		$jyn_install_path/scripts/check_cpplib.sh
	fi

	if [ ! -e /etc/udev/rules.d/90-mtoken.rules ];then
        cp $jyn_install_path/RJJHGLTX/90-mtoken.rules /etc/udev/rules.d/90-mtoken.rules
    fi
	if [ ! -d $jyn_install_path/rtl ] ; then
		mkdir $jyn_install_path/rtl
	fi
	if [ ! -d $jyn_install_path/.quarzone ] ; then
		mkdir $jyn_install_path/.quarzone
	fi
	if [[ -e $jyn_install_path/RJJHGLTX/AuthConfig.dat && -f $jyn_install_path/RJJHGLTX/AuthConfig.dat.old ]] ; then
		rm $jyn_install_path/RJJHGLTX/AuthConfig.dat.old
	fi
	restore $jyn_install_path/RJJHGLTX/AuthConfig.dat
	restore $jyn_install_path/Config/UrlService.ini
	restore $jyn_install_path/RJJHGLTX/UpConfig.ini
	cp_config

    if [ $udisk_flag -ne 1  ] ; then
		if [[ $(is_ui) || $(is_service) ]];then
			if test -f  /etc/xdg/autostart/jingyunsds.desktop ; then
				rm /etc/xdg/autostart/jingyunsds.desktop
			fi

			if test -f /usr/share/applications/jingyunsd.desktop ; then
				rm /usr/share/applications/jingyunsd.desktop
			fi

			if [[ ! -e /etc/xdg/autostart/$desktop_name && -f $jyn_install_path/scripts/${soft_name}_autostart.desktop ]] ;then
				cp $jyn_install_path/scripts/${soft_name}_autostart.desktop /etc/xdg/autostart/$desktop_name
			fi

			if [[ ! -e /usr/share/applications/$desktop_name && -f $jyn_install_path/scripts/${soft_name}_applications.desktop ]] ;then
				cp $jyn_install_path/scripts/${soft_name}_applications.desktop /usr/share/applications/$desktop_name
			fi

			if [ ! -f /usr/share/icons/hicolor/scalable/apps/${soft_name}.svg ] ; then
				sed -i "/^Icon=/cIcon=$jyn_install_path/LOGO/logo_blue.png" /etc/xdg/autostart/$desktop_name
				sed -i "/^Icon=/cIcon=$jyn_install_path/LOGO/logo_blue.png" /usr/share/applications/$desktop_name
			fi

			if [ ! $(is_sdk) ] ; then
				curuser=`$jyn_install_path/cur_user | head -1`

				if [ "$curuser" == "root" ]; then
					desktop_path=/$curuser/Desktop
				else
					desktop_path=/home/$curuser/Desktop
				fi
				if [ ! -d $desktop_path ] ; then
					desktop_path=${desktop_path%/*}/桌面
				fi
				desktop_path=$desktop_path/
				if [[ -d $desktop_path && -f /usr/share/applications/$desktop_name ]] ; then
					cp /usr/share/applications/$desktop_name $desktop_path/$desktop_name
					sed -i "/^NoDisplay=/cNoDisplay=false" $desktop_path/$desktop_name
					chmod -R 777 $desktop_path/$desktop_name
					chown -R $curuser $desktop_path/$desktop_name
					sudo -u $curuser -E gio set $desktop_path/$desktop_name metadata::trusted yes
					echo $desktop_path/$desktop_name > $jyn_install_path/insinfo/desktop_path
				fi
			fi

			#拷贝右键菜单
    		copy_scan_menu
		fi

		# 兼容4004 前版本， 保留隔离区文件
		if [ -d $jyn_install_path/ISO_FILES ];then
			file_num=`ls -l $jyn_install_path/ISO_FILES | wc -l`
			if [ $file_num -gt 1 ];then
				cp -uv $jyn_install_path/ISO_FILES/* $jyn_install_path/.quarzone/
			fi
		fi
	
        #copy install path
        if [[ ! -d "/etc/jyn"   ]]; then
            mkdir /etc/jyn
        fi
    	echo "InstallPath = $jyn_install_path" > /etc/jyn/path.conf
    else
		sed -i "/^VersionType/cVersionType = udisk" $jyn_install_path/Config/Version.ini
        mv $jyn_install_path/run.sh $jyn_install_path/../

		mkdir -p "$jyn_install_path/../Core"
		if [ ! -f  "$jyn_install_path/../Core/Config.ini" ]; then
			mv "$jyn_install_path/Config.ini" "$jyn_install_path/../Core"
		fi
		touch "$jyn_install_path/../Core/Config.ini"

		# U盘管理工具使用
		mkdir -p "$jyn_install_path/../Core/Config"
		echo "VersionType = udisk" > $jyn_install_path/../Core/Config/Version.ini

	    mkdir -p "$jyn_install_path/../Core/RJJHGLTX"
		touch "$jyn_install_path/../Core/RJJHGLTX/AuthConfig.dat"
		# 为了方便U盘管理工具使用，将部分文件拷贝即可
		cp "$jyn_install_path/RJJHGLTX/Vtest.txt" "$jyn_install_path/../Core/RJJHGLTX"

		mkdir -p "$jyn_install_path/../Core/zav"
		if [ ! -d "$jyn_install_path/../Core/zav/zbase" ]; then
			mv "$jyn_install_path/zav/zbase" "$jyn_install_path/../Core/zav"
			mv "$jyn_install_path/zav/jypkgfileinfo" "$jyn_install_path/../Core/zav"
			mv "$jyn_install_path/zav/ZAVUpdate.xml" "$jyn_install_path/../Core/zav"
		else
			rm -rf "$jyn_install_path/zav/zbase"
		fi
		touch "$jyn_install_path/../Core/zav/jypkgfileinfo"
		touch "$jyn_install_path/../Core/zav/ZAVUpdate.xml"

		# 真正需要多平台通用的，通过链接访问
		pwdpath=`pwd`
		cd $jyn_install_path
		ln -sf ../../Core/RJJHGLTX/AuthConfig.dat ./RJJHGLTX/AuthConfig.dat
		ln -sf ../Core/Config.ini ./Config.ini
		ln -sf ../../Core/zav/jypkgfileinfo ./zav/jypkgfileinfo
		ln -sf ../../Core/zav/ZAVUpdate.xml ./zav/ZAVUpdate.xml
		ln -sf ../../Core/zav/zbase ./zav/zbase
		
		ln -sf /tmp/rjjh_gjcz.fd ./RJJHGJCZ/rjjh_gjcz.fd
		cd $pwdpath
    fi

    if [ ! -f "${jyn_install_path}/RJJHetc/JingyunUiConfig.ini" ];then
	    echo setup_time=`date +%s` >> $jyn_install_path/JingyunUiConfig.ini 
        cp "${jyn_install_path}/JingyunUiConfig.ini" ${jyn_install_path}/RJJHetc/
    fi

    echo `dmidecode -t1 | grep Serial\ Number | awk -F: '{print $2}'` > $jyn_install_path/RJJHGLTX/SerialNumber
    # 解决各个系统中的udev库名称不一致的问题
    if [[ ! -d $jyn_install_path/rtl/ ]]; then
    	mkdir -p $jyn_install_path/rtl/
    fi
	ldconfig -p | grep libudev | head -n 1 | awk '{print $4}' | xargs -i ln -sf {} $jyn_install_path/rtl/libudev.so
    if [[ ! -f $jyn_install_path/rtl/libudev.so ]]; then
    	sysUDev=`whereis libudev.so. | awk {'print $2'}`
    	if [[ "$sysUDev"=~"libudev.so" ]] ; then
    		ln -s $sysUDev $jyn_install_path/rtl/libudev.so
    	fi
    fi
}

changmode()
{
    chmod 777 $jyn_install_path
    chmod +x  $jyn_install_path/scripts/*.sh
    chmod +x  $jyn_install_path/scripts/uninstall
    chmod 755 $jyn_install_path/Zy*
    chmod 755 $jyn_install_path/JYN*
	chmod 644 /etc/udev/rules.d/90-mtoken.rules
    chmod 666 $jyn_install_path/Config/*.ini
    chmod 666 $jyn_install_path/*.ini
    chmod 666 $jyn_install_path/*.dat
    chmod 777 $jyn_install_path/zav
    chmod 777 $jyn_install_path/zav/ZAVUpdate.xml
    chmod 777 $jyn_install_path/zav/zbase -R
    chmod 777 $jyn_install_path/RJJHGLTX/ -R
    chmod 777 $jyn_install_path/RJJHGJCZ/ -R
    chmod 777 $jyn_install_path/RJJHZDFY/ -R
    chmod 777 $jyn_install_path/RJJHetc/ -R
    if [ -d $jyn_install_path/.quarzone ] ; then
        chmod 777 $jyn_install_path/.quarzone/ -R
    fi
}

set_startup()
{
	echo "install startup"
	$jyn_install_path/JYNSetStartup install
}

# 功能：检查当前系统如果是新创版本，且当前安装包是非信创版本，则将Type类型改为信创类型
# 修改原因：sdk版本X86_64架构的安装包，以前使用的是非信创版本的Type类型，导致中控扣除授权点数时，只能扣除Linux点数，不能扣除信创点数
check_os_type()
{
	if [ ! $(is_sdk) ] ; then
		echo "check_os_type : no processing required: not sdk "
		return
	fi

	origin_type=$(cat $jyn_install_path/Config/Version.ini | grep Type | grep -v VersionType)
	# 非X86_64标准版 不检查
	if [[ ${origin_type:12:1} != "0" || ${origin_type:14:1} != "2" ]] ; then
		echo "check_os_type : no processing required: arch:${origin_type:12:1} type:${origin_type:14:1} "
		return
	fi

	system_info=""
	if test -f /etc/os-release ; then
		system_info=`cat /etc/os-release | grep PRETTY_NAME | awk -F= '{print $2}' | sed 's/"//g'`
	fi
	if test -f /etc/system-release ; then
		system_info=`cat /etc/system-release`
	fi

	cat $jyn_install_path/RJJHGLTX/OsConfig.dat | while IFS= read -r line; do
		os_value=$(echo $line | awk -F= '{print $1}')
		if [[ "e$os_value" != "e" && "$system_info" =~ "$os_value" ]] ; then
			new_type=$(awk -v idx="15" -v char="4" 'BEGIN {FS = ""} {OFS = ""} NR==1 { $idx = char; print }' <<< "$origin_type")
			sed -i "/^Type = /c$new_type" $jyn_install_path/Config/Version.ini
			echo "check_os_type : os_v:$os_value sys_v:$system_info ori_t:$origin_type new_t:$new_type"
			return
		fi
	done
	echo "check_os_type : failure!!! sys_v:$system_info"
}

recover_dir()
{
	if test -d /var/jyn/backups/$jyn_install_path ; then
		cp -rf /var/jyn/backups/$jyn_install_path/* $jyn_install_path
		rm -rf /var/jyn/backups/$jyn_install_path
	fi
}

case "$1" in
    udisk)
        udisk_flag=1
        cp_file
        changmode
        ;;
    *)
		recover_dir
        cp_file
        changmode
        set_startup
        set_ip_or_domain
        check_local_version
		smui_config
		check_os_type
        start_run
        ;;
esac

