#!/bin/bash

current_script=$(cd `dirname $0`;pwd)
jyn_install_path=$(dirname "$current_script")

log_dir="$jyn_install_path/log/"
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"
inslog="${ins_info_dir}/sd_ins_log"
ppid=$1

is_ui()
{
    if [ -e "$jyn_install_path/bin/JYNRJJH2" ]; then
        echo "1"
    fi
}

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

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

is_uos()
{
    issueinfo=`cat /etc/issue`
    if [[ $issueinfo =~ "uos" || $issueinfo =~ "UOS" || $issueinfo =~ "UnionTech" ]] ; then
        echo "1"
    fi
}

is_kylin_v11()
{
    if [[ -f /etc/os-release ]] && [[ "`cat /etc/os-release`" =~ "Kylin V11" ]] ; then
        echo "1"
    fi
}


# 检查 IPv6 的实现
check_v6() {
    local input=$1
    local ipv6
    ipv6=$(echo "$input" | grep -E -o 'ip([0-9a-fA-F]{0,4}x){1,7}[0-9a-fA-F]{0,4}')
    if [ -n "$ipv6" ]; then
        ipv6=${ipv6//x/:}
        ipv6=${ipv6##*ip}
        echo "[$ipv6]"
    else
        ipv6=$(echo "$input" | grep -E -o '([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}')
        [ -n "$ipv6" ] && echo "[$ipv6]" || echo ""
    fi
}

# 检查 IP 或域名
check_ip_or_domain() {
    local XPPID=$ppid
    package="$DPKG_MAINTSCRIPT_PACKAGE"
    echo "package:"$package >> $inslog
    packinfo=$(ps -ef|awk '{ if($2=='$XPPID') {print}}' | grep -o ''$package'[^ ]*')
    echo "packinfo:"$packinfo >> $inslog
    if [ -z "$packinfo" ]; then
        filename=$(ps -ef|awk '{ if($2=='$XPPID') {print $10}}')
        echo "print 10 processname:"$filename >> $inslog
    else
        filename=$packinfo
        echo "packinfo processname:"$filename >> $inslog
    fi
    filename=${filename##*/}
    echo "Process name:$filename"
    local ip=$(echo "$filename" | grep -E -o "ip[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | grep -E -o "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")
    [ -z "$ip" ] && ip=$(check_v6 "$filename")
    # 处理 IP 为空的情况
    if [ -z "$ip" ]; then
        echo "" > "$ccip"
    else
        # 写入 IP 到 ccip
        echo "$ip" > "$ccip"
    fi

    # 匹配版本号
    if [[ "$str" =~ (_c[0-9]+\.[0-9]{4}\.[0-9]\.[0-9]{4}_) ]]; then
        version="${BASH_REMATCH[1]}"
        echo "match client type: $version"
        sed -i "/^Type =/cType = ${version}" "$jyn_install_path/etc/Version.ini"
    fi
}

set_ip_or_domain()
{
	  echo setup_time=`date +%s` >> $jyn_install_path/etc/JingyunUiConfig.ini
	  if [ -f $ccip ]; then
		    ip=`cat $ccip`
		    if [ "$ip" != "" ]; then
		        echo "ServiceUrl.10 = http://$ip" > $jyn_install_path/etc/UrlService.ini
		        echo "Url.1 = http://$ip" >> $jyn_install_path/etc/UrlService.ini
		    fi
	  fi
}

check_local_version(){
    if [ -f /etc/issue ] ;then
        local_version=$(cat /etc/issue | grep "Ubuntu 14.04")
        if [ "$local_version"e != ""e ]; then
            echo $local_version
            UdiskScan=$(cat $jyn_install_path/etc/UiConfig.ini | grep "UdiskScan")
            if [ "$UdiskScan"e != ""e ]; then
                sed -i "/^Udisk/cUdiskScan = 0" $jyn_install_path/etc/UiConfig.ini
            else 
                echo "UdiskScan = 0" >> $jyn_install_path/etc/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
        #    cur_user=`$jyn_install_path/bin/cur_user | head -1`
        #    sudo -u $cur_user -E gio set $desktop_path/JYNRJJH2.desktop metadata::trusted true
        #    echo $desktop_path/JYNRJJH2.desktop >> $ins_info_dir/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/bin/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

	if command_exists nemo ; then
		echo "copy nemo files"
		if [ "$(is_sm)"e == "1"e ] ; then
			ln -f $jyn_install_path/tools/gjyn/nemo/jynscan.nemo_action /usr/share/nemo/actions/
		else
			cp $jyn_install_path/tools/gjyn/nemo/jynscan.nemo_action /usr/share/nemo/actions/
		fi
		echo "/usr/share/nemo/actions/jynscan.nemo_action" > $rs_path
        return
	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/tools/gjyn/dde/deepin-chenxinsd.desktop  /usr/share/deepin/dde-file-manager/oem-menuextensions/
		else
			cp $jyn_install_path/tools/gjyn/dde/deepin-chenxinsd.desktop  /usr/share/deepin/dde-file-manager/oem-menuextensions/
		fi
		echo "/usr/share/deepin/dde-file-manager/oem-menuextensions/deepin-chenxinsd.desktop" > $rs_path
        return
	fi

	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
            # 兼容麒麟V11
            if [ -f /etc/os-release ] && [ -d /opt/system/lib/peony-extensions ]; then
                system=`cat /etc/os-release | grep "VERSION_US=" | cut -d '=' -f 2`
                if [[ $system =~ "Kylin" ]]; then
                    lib_target_dir="/opt/system/lib/peony-extensions"
		    # 兼容龙芯架构下的新peony库
                    if [[ "`arch`" == "loongarch64" ]] && [ -f ${jyn_install_path}/tools/gjyn/$each/libpeony-gjyn.so ] && [ -f ${jyn_install_path}/tools/gjyn/$each/libpeony-gjyn-newky.so ]; then
                            mv ${jyn_install_path}/tools/gjyn/$each/libpeony-gjyn-newky.so ${jyn_install_path}/tools/gjyn/$each/libpeony-gjyn.so
                    fi

                fi
            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}/tools/gjyn/$each/libpeony-gjyn.so ] && [ -f ${jyn_install_path}/tools/gjyn/$each/libpeony-gjyn-3.10.0.so ]; then
                            mv ${jyn_install_path}/tools/gjyn/$each/libpeony-gjyn-3.10.0.so ${jyn_install_path}/tools/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/tools/gjyn/$each ]; then
                    rs_lib_name=`ls $jyn_install_path/tools/gjyn/$each/*`
                    rs_lib_name=${rs_lib_name##*/}
                fi
                if [ -f $jyn_install_path/tools/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/tools/gjyn/$each/$rs_lib_name $lib_target_dir
                    else
                        cp $jyn_install_path/tools/gjyn/$each/$rs_lib_name $lib_target_dir
                    fi
                    echo "$lib_target_dir/$rs_lib_name" > $rs_path
                fi
                return
            fi
		fi
	done
}

start_run()
{
	#不自动拉起服务
	if [ -f $nostart_path ] && [ "`cat $nostart_path`" != "" ]; then
		return
	fi

	arr_svr_name=(jynsafed jynzdfy)
	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_sdk) ]] ; then
        set_xdg_runtime_dir
        if [ -f $jyn_install_path/bin/cur_user ]; then
            #统信V25环境，桌面双击安装后，软件图标变为系统包管理器的图标，重启后正常；
            #为解决上述问题，安装时直接重启, 第一次用hide参数保证用户无感知
            sudo -u `$jyn_install_path/bin/cur_user | head -1` -H -E $jyn_install_path/scripts/JYNRJJH1 --hide >> /tmp/JYStartInstall.log 2>&1 &
            while true; do
                  pid=$(pgrep -x JYNRJJH2)
                  if [[  "$pid"e != ""e ]]; then
                          echo $pid
                          $(kill -9 $pid)
                          break;
                  else
                          sleep 1
                  fi
            done
            echo "restart JYNRJJH"
            sudo -u `$jyn_install_path/bin/cur_user | head -1` -H -E $jyn_install_path/scripts/JYNRJJH1 >> /tmp/JYStartInstall.log 2>&1 &
        fi
    fi
  }

  cp_config()
  {
    if [ ! -f $jyn_install_path/etc/Config.ini ]; then
        touch $jyn_install_path/etc/Config.ini
    fi
    sed -i '/InstallVersion/d' $jyn_install_path/etc/Config.ini
    sed -i '/Type/d' $jyn_install_path/etc/Config.ini
    sed -i "/^SelfProtect/cSelfProtect = 1" $jyn_install_path/etc/Config.ini
  }

  check_libc()
  {
    if test -f $jyn_install_path/scripts/check_libc.sh ; then
      $jyn_install_path/scripts/check_libc.sh
    fi
  }

  check_std()
  {
    if test -f $jyn_install_path/scripts/check_cpplib.sh ; then
      $jyn_install_path/scripts/check_cpplib.sh
    fi
  }

cp_desktop()
{
    curuser=`$jyn_install_path/bin/cur_user | head -1`
    if [ -d "/$curuser" ]; then
        desktop_path="/$curuser/Desktop"
    else
        desktop_path="/home/$curuser/Desktop"
    fi
    if [ ! -d $desktop_path ] ; then
        desktop_path=${desktop_path%/*}/桌面
    fi

    source_path=/usr/share/applications/JYNRJJH2.desktop
    desktop_name="JYNRJJH2.desktop"
    
    #删除老版本的快捷方式
    dskpath=`cat $jyn_install_path/insinfo/desktop_path | head -1`
    if [[ "$dskpath"e != ""e && -f $dskpath ]] ; then
        rm $dskpath
    fi
    if test -e $desktop_path/JYNRJJH2.desktop ; then
        rm -f $desktop_path/JYNRJJH2.desktop
    fi
    if test -e $desktop_path/jingyunsd.desktop ; then
        rm -f $desktop_path/jingyunsd.desktop
    fi
    if test -e $desktop_path/chenxinsd.desktop ; then
        rm -f $desktop_path/chenxinsd.desktop
    fi
    if test -e $desktop_path/vrvsd.desktop ; then
        rm -f $desktop_path/vrvsd.desktop
    fi

	if [[ -d $desktop_path ]] && `ls $source_path >/dev/null 2>&1` ; then
        echo "cp $source_path $desktop_path/$desktop_name"
		cp $source_path $desktop_path/$desktop_name
		sed -i "/^NoDisplay=/cNoDisplay=false" $desktop_path/$desktop_name
		chmod -R 755 $desktop_path/$desktop_name
		chown -R $curuser $desktop_path/$desktop_name
		sudo -u $curuser -E gio set $desktop_path/$desktop_name metadata::trusted yes
        mkdir -p $jyn_install_path/insinfo
		echo $desktop_path/$desktop_name > $jyn_install_path/insinfo/desktop_path
	fi

    auto_desktop_target=/etc/xdg/autostart
    # 麒麟V11 系统"/opt/system/resource/applications/"目录可能存在问题，暂时去掉该目录，统一使用/usr中的
    # # 兼容麒麟V11
	# if [[ $(is_kylin_v11) ]] ; then
    #     rm -rf /usr/share/applications/JYNRJJH2.desktop
    # fi
    # if [ -f /etc/os-release ] && [ -d /opt/system/conf/xdg/autostart ]; then
    #     system=`cat /etc/os-release | grep "VERSION_US=" | cut -d '=' -f 2`
    #     [[ $system =~ "Kylin" ]] && auto_desktop_target=/opt/system/conf/xdg/autostart
    # fi

    # UOS
	if [[ $(is_uos) ]] ; then
        auto_desktop_target=""
    fi
    # autostart
    if [ -n "$auto_desktop_target" ]; then
        echo "copy autostart desktop to $auto_desktop_target"
        cp -f $jyn_install_path/../entries/autostart/JYNRJJH2.desktop  $auto_desktop_target/ > /dev/null 2>&1
    fi

}

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

    # check_libc
    # check_std
    if [ ! -e /etc/udev/rules.d/90-mtoken.rules ];then
          cp $jyn_install_path/tools/udev/rules.d/90-mtoken.rules /etc/udev/rules.d/90-mtoken.rules
    fi

    cp_config
    copy_scan_menu

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

    echo `dmidecode -t1 | grep Serial\ Number | awk -F: '{print $2}'` > $jyn_install_path/etc/RJJHGLTX/SerialNumber
    # 解决各个系统中的udev库名称不一致的问题
    ldconfig -p | grep libudev | head -n 1 | awk '{print $4}' | xargs -i ln -sf {} $jyn_install_path/lib/externals/libudev.so
    # 判断是否存在qt库，存在使用系统的qt库
    if pkg-config --exists Qt5Core; then
        # UOS 20 服务器虽然有Qt 但使用存在问题，所以用自带的
        if [[ -f /etc/os-release ]] && [[ "`cat /etc/os-release`" =~ "UnionTech OS Server 20" ]]; then
            echo "The system is UnionTech OS Server 20. Use the library of the installation package."
        else
            echo "The system has installed the Qt library, and the system library is used."
            mv $jyn_install_path/lib/externals/qt $jyn_install_path/lib/externals/qt.d
        fi
    else
        # 虽然 pkg-config 未返回成功，但 Kylin V11 自带Qt，使用我们自带的会有问题
        if [[ -f /etc/os-release ]] && [[ "`cat /etc/os-release`" =~ "Kylin V11" ]]; then
            echo "The system has installed the Qt library, and the system library is used."
            mv $jyn_install_path/lib/externals/qt $jyn_install_path/lib/externals/qt.d
        else
            echo "The Qt library is not installed in the system. Use the library of the installation package."
        fi
    fi

    # 麒麟V11 arm版本 暂时去掉 libX11.so的动态库，界面启动时会报错
    # if [[ -f /etc/os-release ]] && [[ "`cat /etc/os-release`" =~ "Kylin V11" ]] && [[ "`uname -a`" =~ "aarch" ]]; then

    # 暂时将arm架构全部去掉X11库，看是否会遇到某些系统有问题
    if [[ "`uname -a`" =~ "aarch" ]]; then
        rm $jyn_install_path/lib/externals/qt/lib/libX11.so*
    fi

    cp_desktop
}

  changmode()
  {
      # todo: 必须将这三个设为777，不然界面第一次启动不起来，尚待解决
      chmod 777 $jyn_install_path
      chmod 777 $jyn_install_path/bin
      chmod 755 $jyn_install_path/bin/*
      chmod 777 $jyn_install_path/bin/JYNRJJH2
      chmod +x  $jyn_install_path/scripts/*.sh
      chmod +x  $jyn_install_path/scripts/JYNInstall
    chmod +x  $jyn_install_path/scripts/JYNSetStartup
    chmod +x  $jyn_install_path/scripts/JYNUninstall
    chmod 644 $jyn_install_path/etc/*.ini
    chmod 755 $jyn_install_path/lib/ -R
    chmod 755 $jyn_install_path/etc/ -R
    chmod 777 $log_dir -R
    #chmod 755 $jyn_install_path/bin/ -R
    if [ -d $jyn_install_path/.quarzone ] ; then
        chmod 700 $jyn_install_path/.quarzone/ -R
    fi
	  chown -R root:root $jyn_install_path
}

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

#TODO 这里恢复，没有考虑到数据库或者配置中字段变化的时候，后续要结合字段变化做兼容处理
restore_backup_data_708()
{
    #移动隔离区的数据到安装目录
 	  if [ -d $1/.quarzone ] ; then
 	      mv $1/.quarzone $jyn_install_path/
 	  fi

 	  if [ -f $1/etc/RJJHGJCZ/black_list.db ] ; then
     	  mv $1/etc/RJJHGJCZ/black_list.db $jyn_install_path/etc/RJJHGJCZ/
    fi
    if [ -f $1/etc/RJJHGJCZ/iso_area.db ] ; then
     	  mv $1/etc/RJJHGJCZ/iso_area.db $jyn_install_path/etc/RJJHGJCZ/
    fi
    if [ -f $1/etc/RJJHGJCZ/white_list.db ] ; then
        mv $1/etc/RJJHGJCZ/white_list.db $jyn_install_path/etc/RJJHGJCZ/
    fi
    #移动驱动配置
    if [ -f $1/etc/RJJHZDFY/DriverConfig.ini ] ; then
        sed -i "/^NormalExit/cNormalExit = 1" $1/etc/RJJHZDFY/DriverConfig.ini
        mv $1/etc/RJJHZDFY/DriverConfig.ini $jyn_install_path/etc/RJJHZDFY/
    fi
    #移动中控信息
 	  if [ -f $1/etc/UrlService.ini ] ; then
 	      mv $1/etc/UrlService.ini $jyn_install_path/etc/
    fi
    #移动防护日志
    if [ -f $1/cache/zy_protect_log.db ] ; then
    	  mv $1/cache/zy_protect_log.db $jyn_install_path/cache/
    fi
    #移动终端信息
    if [ -f $1/cache/jy_terminal_details.sqlite ] ; then
    	  mv $1/cache/jy_terminal_details.sqlite $jyn_install_path/cache/
    fi

    if [ -f $1/cache/jy_terminal_sys_config.sqlite ] ; then
    	  mv $1/cache/jy_terminal_sys_config.sqlite $jyn_install_path/cache/
    fi
    #授权
    if [ -f $1/etc/RJJHGLTX/AuthConfig.dat ] ; then
    	  mv $1/etc/RJJHGLTX/AuthConfig.dat  $jyn_install_path/etc/RJJHGLTX/
    fi
    #移动定时任务
    if [ -f $1/cache/timed_tasks.db ] ; then
        mv $1/cache/timed_tasks.db $jyn_install_path/cache/
    fi
}

# 移除705/707的右键查杀
clear_705_707_scan_menu()
{
    echo "rm scan_menu"
    bcakup_rs_path="$1/insinfo/rspath"
    if test -e $bcakup_rs_path ; then
		echo "rm `cat $bcakup_rs_path`"
        rm `cat $bcakup_rs_path`
    fi

    file_menu_suport_list="/usr/share/nemo/actions/jynscan.nemo_action
    /usr/share/deepin/dde-file-manager/oem-menuextensions/deepin-chenxinsd.desktop
    /usr/share/deepin/dde-file-manager/oem-menuextensions/com.vsecure.chenxinsd.desktop"    # uos的右键库名字特殊

    for each in $file_menu_suport_list 
    do 
        if test -e $each ; then 
            echo "remove $each"
            rm $each
        fi
    done
}

stop_705_svr()
{
	arr_svr_name=(jyngjcz jyngltx jynzdfy jynengsvr jynproc)
	for svr_name in ${arr_svr_name[@]}; do
		#服务配置文件是在set_startup被拷贝的
		if command -v "systemctl" &> /dev/null ; then
			if [ "`systemctl list-unit-files | grep $svr_name.service`" != "" ] ;then
				systemctl stop $svr_name
			fi
		elif test -f /etc/init.d/$svr_name ; then			
				service $svr_name stop
		fi
	done

	#异常容错,kill掉依旧存在的进程
	if `pidof JYNGJCZ2 > /dev/null`; then
		kill -9 `pidof JYNGJCZ2`
	fi
	if `pidof JYNGLTX1 > /dev/null`; then
		kill -9 `pidof JYNGLTX1`
	fi
	if `pidof JYNPROC1 > /dev/null`; then
		kill -9 `pidof JYNPROC1`
	fi
	if `pidof filemonitor > /dev/null`; then
		kill -9 `pidof filemonitor`
	fi
	if `pidof jy_tasksvr > /dev/null`; then
		kill -9 `pidof jy_tasksvr`
	fi
	if `pidof JingyunsdIPCServer > /dev/null`; then
		kill -9 `pidof JingyunsdIPCServer`
	fi
	if `pidof JingyunSdCtrlCenter > /dev/null`; then
		kill -9 `pidof JingyunSdCtrlCenter`
	fi

	#驱动在确保JYNZDFY2(filemonitor)关闭之后进行卸载 防止因为被使用
	#进而导致卸载失败遗留系统中影响系统性能 或 导致下一次驱动安装失败
	smUi=`grep "ZYJ = 1" $1/Config/Version.ini | awk '{print $3}' | tr -d "\n"`
	if [ -n "${smUi}" ] ; then
		#卸载内核模块
		KO_PATH=$1/ZDFY001.ko
		if test -e $KO_PATH ; then
			rmmod ZDFY001
		fi
	fi
}

stop_705_run()
{
	echo "stop 705"
	stop_705_svr $1
	if [ -f $1/filemonitor ]; then
		$1/filemonitor stopSelfProtect
	fi
	if `pidof JYNRJJH2 > /dev/null`; then
		echo "stop JYNRJJH"
		kill -9 `pidof JYNRJJH2`
	fi
	if `pidof ZyUDiskTray_UI > /dev/null`; then
		echo "stop ZyUDiskTray_UI"
		kill -9 `pidof ZyUDiskTray_UI`
	fi
}

restore_backup_data_705()
{
    #由于705prerm没有针对升级做相应的关闭进程等操作，此处进行处理
    stop_705_run $1
    clear_705_707_scan_menu $1  
    #移动隔离区的数据到安装目录
    if [ -d $1/.quarzone ] ; then
        mv $1/.quarzone $jyn_install_path/
    fi
    #移动授权
    if [ -f $1/RJJHGLTX/AuthConfig.dat ] ; then
    	  mv $1/RJJHGLTX/AuthConfig.dat  $jyn_install_path/etc/RJJHGLTX/
    fi
    #移动隔离区与信任区
    if [ -f $1/RJJHGJCZ/iso_area.db ] ; then
        mv $1/RJJHGJCZ/iso_area.db $jyn_install_path/etc/RJJHGJCZ/
    fi
    if [ -f $1/RJJHGJCZ/white_list.db ] ; then
        if [ -f $jyn_install_path/bin/JYN-VERSION-COMPATIBLE ] ; then
            $jyn_install_path/bin/JYN-VERSION-COMPATIBLE --migrate-version 7.0.0.5 --sync-white-list
        fi
    fi
    #移动中控信息
    if [ -f $1/Config/UrlService.ini ] ; then  
     	  mv $1/Config/UrlService.ini $jyn_install_path/etc/
    fi
    #防护日志
    if [ -f $1/RJJHetc/zy_protect_log.db ] ; then
        if [ -f $jyn_install_path/bin/JYN-VERSION-COMPATIBLE ] ; then
            $jyn_install_path/bin/JYN-VERSION-COMPATIBLE --migrate-version 7.0.0.5 --sync-protect-log
        fi
    fi
    #记录病毒库升级标识，用于软件升级完成后，升级病毒库
    if [ -f $jyn_install_path/bin/JYN-VERSION-COMPATIBLE ] ; then
        $jyn_install_path/bin/JYN-VERSION-COMPATIBLE --migrate-version 7.0.0.5 --update-virus-library
    fi
    #同步配置
    if [ -f $1/Config.ini ] ; then
        if [ -f $jyn_install_path/bin/JYN-VERSION-COMPATIBLE ] ; then
            $jyn_install_path/bin/JYN-VERSION-COMPATIBLE --migrate-version 7.0.0.5 --sync-sys-config
        fi
    fi
}


stop_707_svr()
{
	arr_svr_name=(jyngjcz jyngltx jynzdfy jynengsvr jynproc)
	for svr_name in ${arr_svr_name[@]}; do
		#服务配置文件是在set_startup被拷贝的
		if command -v "systemctl" &> /dev/null ; then
			if [ "`systemctl list-unit-files | grep $svr_name.service`" != "" ] ;then
				systemctl stop $svr_name
			fi
		elif test -f /etc/init.d/$svr_name ; then			
				service $svr_name stop
		fi
	done

	#异常容错,kill掉依旧存在的进程
	if `pidof JYNGJCZ2 > /dev/null`; then
		kill -9 `pidof JYNGJCZ2`
	fi
	if `pidof JYNGLTX1 > /dev/null`; then
		kill -9 `pidof JYNGLTX1`
	fi
	if `pidof JYNPROC1 > /dev/null`; then
		kill -9 `pidof JYNPROC1`
	fi
	if `pidof filemonitor > /dev/null`; then
		kill -9 `pidof filemonitor`
	fi
	if `pidof jy_tasksvr > /dev/null`; then
		kill -9 `pidof jy_tasksvr`
	fi

	#驱动在确保JYNZDFY2(filemonitor)关闭之后进行卸载 防止因为被使用
	#进而导致卸载失败遗留系统中影响系统性能 或 导致下一次驱动安装失败
	smUi=`grep "ZYJ = 1" $1/Config/Version.ini | awk '{print $3}' | tr -d "\n"`
	if [ -n "${smUi}" ] ; then
		#卸载内核模块
		KO_PATH=$1/ZDFY001.ko
		if test -e $KO_PATH ; then
			rmmod ZDFY001
		fi
	fi
}

stop_707_run()
{
	echo "stop 707"
	stop_707_svr $1
	if [ -f $1/filemonitor ]; then
		$1/filemonitor stopSelfProtect
	fi

    if `pidof JYNRJJH2 > /dev/null`; then
        if test -f $1/JYNRJJH2 ; then
            $1/JYNRJJH2 --exit
        fi
        if `pidof JYNRJJH2 > /dev/null`; then
            kill -9 `pidof JYNRJJH2`
        fi
    fi
	if `pidof JYNRJJH2-UTRAY > /dev/null`; then
		echo "stop JYNRJJH2-UTRAY"
		kill -9 `pidof JYNRJJH2-UTRAY`
	fi
}

restore_backup_data_707()
{
    stop_707_run $1
    clear_705_707_scan_menu $1
    #移动隔离区的数据到安装目录
    if [ -d $1/.quarzone ] ; then
        mv $1/.quarzone $jyn_install_path/
    fi
    #移动授权
    if [ -f $1/RJJHGLTX/AuthConfig.dat ] ; then
    	  mv $1/RJJHGLTX/AuthConfig.dat  $jyn_install_path/etc/RJJHGLTX/
    fi
    #移动隔离区与信任区
    if [ -f $1/RJJHGJCZ/iso_area.db ] ; then
        mv $1/RJJHGJCZ/iso_area.db $jyn_install_path/etc/RJJHGJCZ/
    fi
    if [ -f $1/RJJHGJCZ/white_list.db ] ; then
        mv $1/RJJHGJCZ/white_list.db $jyn_install_path/etc/RJJHGJCZ/
    fi
    #移动中控信息
    if [ -f $1/Config/UrlService.ini ] ; then
     	  mv $1/Config/UrlService.ini $jyn_install_path/etc/
    fi
    #防护日志
    if [ -f $1/RJJHetc/zy_protect_log.db ] ; then
        if [ -f $jyn_install_path/bin/JYN-VERSION-COMPATIBLE ] ; then
            $jyn_install_path/bin/JYN-VERSION-COMPATIBLE --migrate-version 7.0.0.7 --sync-protect-log
        fi
    fi
    #记录病毒库升级标识，用于软件升级完成后，升级病毒库
    if [ -f $jyn_install_path/bin/JYN-VERSION-COMPATIBLE ] ; then
        $jyn_install_path/bin/JYN-VERSION-COMPATIBLE --migrate-version 7.0.0.7 --update-virus-library
    fi
    #同步配置
    if [ -f $1/Config.ini ] ; then
        if [ -f $jyn_install_path/bin/JYN-VERSION-COMPATIBLE ] ; then
            $jyn_install_path/bin/JYN-VERSION-COMPATIBLE --migrate-version 7.0.0.7 --sync-sys-config
        fi
    fi
}

restore_backup_data()
{
    # 定义备份目录路径
    BACKUP_DIR="/tmp/jyn_install_path_backup_dir"
    # 在备份目录中查找 Version.ini 文件, 注：705之前的版本配置文件在Config.ini中
    version_ini_files=$(find "$BACKUP_DIR" \( -name 'Version.ini' -o -name 'Version.ini.old' \))
    # 检查是否找到了 Version.ini 文件
    if [ -z "$version_ini_files" ]; then
        echo "未在 '$BACKUP_DIR' 中找到 Version.ini 文件。"
        version_ini_files=$(find "$BACKUP_DIR" -name 'Config.ini')
        if [ -z "$version_ini_files" ]; then
            echo "未在 '$BACKUP_DIR' 中找到 Config.ini 文件。"
            rm $BACKUP_DIR -r
            return
        fi
    fi
    echo "find Version.ini file： $version_ini_files"
    # 从配置文件中读取 InstallVersion 的值
    install_version=$(grep '^InstallVersion' "$version_ini_files" | awk -F ' = ' '{print $2}')
    # 检查是否成功读取 InstallVersion
    if [ -z "$install_version" ]; then
        echo "无法读取 InstallVersion，请检查配置文件格式。"
        rm $BACKUP_DIR -r
        return
    fi
    # 获取主版本号部分（假设为前7个字符）
    main_version=${install_version:0:7}
    if [ "$main_version" == "7.0.0.8" ]; then
        echo "InstallVersion is 7.0.0.8."
        restore_backup_data_708 $BACKUP_DIR
    elif [ "$main_version" == "3.0.8.0" ]; then
        echo "InstallVersion is 3.0.8.0."
        restore_backup_data_708 $BACKUP_DIR
    elif [ "$main_version" == "7.0.0.7" ]; then
        echo "InstallVersion is 7.0.0.7."
        restore_backup_data_707 $BACKUP_DIR
    # 低于705的版本也走705的备份处理流程
    elif [ ! -z "$main_version" ]; then
        echo "InstallVersion is $main_version."
        restore_backup_data_705 $BACKUP_DIR
    else
        echo "InstallVersion $install_version."
    fi
    rm $BACKUP_DIR -r
}


set_data()
{
    if [ ! -d "$log_dir" ]; then
        mkdir -p "$log_dir"
    fi

    if [ ! -d "$ins_info_dir" ]; then
        mkdir -p "$ins_info_dir"
    fi
    #检测是否存在安装残留
    local backup_dir="/tmp/jyn_install_path_backup_dir"
    local uninstall_backup_tar_file="/var/jyn/jyn_uninstall_config_backup.tar"  # 708备份路径
    local uninstall_backup_705="/var/jyn/backups/opt/apps/cn.vsecure.chenxinsd/files" # 705和707备份路径
    if [ -f "$uninstall_backup_tar_file" ] && [ ! -d "$backup_dir" ] ; then
        #发现安装残留，解压到备份目录，进行恢复
        echo "Uninstall residue found, restore..."
        if mkdir -p "$backup_dir"; then
            tar -xpf "$uninstall_backup_tar_file" -C "$backup_dir" && {
                echo "Success: Files extracted to $backup_dir"
                rm  -f "$uninstall_backup_tar_file" || {
                    echo "Warning deletion failed $uninstall_backup_tar_file" >&2
                }
            }
        else
            echo "Error: Failed to create directory $backup_dir" >&2
        fi
    elif [ -d "$uninstall_backup_705" ] && [ ! -d "$backup_dir" ]; then
        echo "Uninstall residue found in $uninstall_backup_705, restore..."
        if mkdir -p "$backup_dir"; then
            cp -r "$uninstall_backup_705"/* "$backup_dir" && {
                echo "Success: Files copied to $backup_dir"
            }
        else
            echo "Error: Failed to create directory $backup_dir" >&2
        fi
    fi

    # 若是旧版本需要使用同步工具，则需要先拷贝C++库
    check_libc
    check_std
    if [ -d "$backup_dir" ]; then
        restore_backup_data
    fi

    cp_file
}

# 安装时尝试删除残留的桌面快捷方式
# 旧版本升级，桌面快捷方式不会被删除
rm_desktop(){
	curuser=`$jyn_install_path/bin/cur_user | head -1`
	if [ -d "/$curuser" ]; then
		desktop_path="/$curuser/Desktop"
	else
		desktop_path="/home/$curuser/Desktop"
	fi
	if [ ! -d $desktop_path ] ; then
		desktop_path=${desktop_path%/*}/桌面
	fi
    if [ -e "$desktop_path/JYNRJJH2.desktop" ]; then
        rm -rf "$desktop_path/JYNRJJH2.desktop"
    fi
    if [ -e "$desktop_path/chenxinsd.desktop" ]; then
        rm -rf "$desktop_path/chenxinsd.desktop"
	fi
    if [ -e "$desktop_path/com.vsecure.chenxinsd.desktop" ] ; then
        rm -rf "$desktop_path/com.vsecure.chenxinsd.desktop"
    fi
}

# 功能：由于授权分为Linux授权和国产化授权，所以检查当前系统如果是非信创版本，则将client type类型x.xxxx.4.xxxx 改为 x.xxxx.2.xxxx
check_os_type() {
    # 读取 Type 字段
    origin_type=$(grep -E '^Type' "$jyn_install_path/etc/Version.ini" | grep -v VersionType)

    # 非X86架构不检查
    arch_char="${origin_type:12:1}"
    if [[ "$arch_char" != "0" && "$arch_char" != "1" ]]; then
        return
    fi

    echo "check os type : arch:$(arch)"

    # 获取系统信息
    system_info=""
    if [[ -f /etc/os-release ]]; then
        system_info=$(grep PRETTY_NAME /etc/os-release | awk -F= '{print $2}' | tr -d '"')
    elif [[ -f /etc/system-release ]]; then
        system_info=$(cat /etc/system-release)
    fi

    # 检查是否在国产化列表中
    if [[ -f "$jyn_install_path/etc/RJJHGLTX/OsConfig.dat" ]]; then
        while IFS='=' read -r os_value _; do
            [[ -n "$os_value" && "$system_info" =~ "$os_value" ]] && return
        done < "$jyn_install_path/etc/RJJHGLTX/OsConfig.dat"
    fi

    # 修改 Version.ini 中 Type 的第三段
    sed -i -E 's/^(Type = [0-9]+[.-][0-9]{4}[.-])4([.-][0-9]{4})/\12\2/' "$jyn_install_path/etc/Version.ini"
    echo "check os type replace type, sys info:$system_info"

    autostart_desktop="/etc/xdg/autostart/JYNRJJH2.desktop"
    applications_desktop="/usr/share/applications/JYNRJJH2.desktop"
    sed -i '/Name\[zh_CN\]/cName\[zh_CN\]=辰信景云终端安全管理系统V7.0' $autostart_desktop $applications_desktop
}

rm_desktop
check_os_type
set_data
changmode
set_startup
check_ip_or_domain
set_ip_or_domain
check_local_version
start_run
