#!/bin/bash
sh_ver=0.0.3

red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'

Green_font_prefix="\033[32m" && Red_font_prefix="\033[31m" && Green_background_prefix="\033[42;37m" && Red_background_prefix="\033[41;37m" && Font_color_suffix="\033[0m"
Info="${Green_font_prefix}[信息]${Font_color_suffix}"
Error="${Red_font_prefix}[错误]${Font_color_suffix}"
Tip="${Green_font_prefix}[注意]${Font_color_suffix}"

cur_dir=$(pwd)
config_platform_file="/data/configs/platform.conf"
config_device_file="/data/configs/device_list.conf"

# check root
[[ $EUID -ne 0 ]] && echo -e "${red}错误：${plain} 必须使用root用户运行此脚本！\n" && exit 1

# check os
check_sys(){
	if [[ -f /etc/redhat-release ]]; then
		release="centos"
	elif cat /etc/issue | grep -q -E -i "debian"; then
		release="debian"
	elif cat /etc/issue | grep -q -E -i "ubuntu"; then
		release="ubuntu"
	elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat"; then
		release="centos"
	elif cat /proc/version | grep -q -E -i "debian"; then
		release="debian"
	elif cat /proc/version | grep -q -E -i "ubuntu"; then
		release="ubuntu"
	elif cat /proc/version | grep -q -E -i "centos|red hat|redhat"; then
		release="centos"
    fi
	bit=`uname -m`
}

arch=$(arch)

if [[ $arch == "x86_64" || $arch == "x64" || $arch == "amd64" ]]; then
  arch="64"
elif [[ $arch == "aarch64" || $arch == "arm64" ]]; then
  arch="arm64-v8a"
else
  arch="64"
  echo -e "${red}检测架构失败，使用默认架构: ${arch}${plain}"
fi

# echo "架构: ${arch}"

if [ "$(getconf WORD_BIT)" != '32' ] && [ "$(getconf LONG_BIT)" != '64' ] ; then
    echo "本软件不支持 32 位系统(x86)，请使用 64 位系统(x86_64)"
    exit 2
fi

os_version=""

# os version
if [[ -f /etc/os-release ]]; then
    os_version=$(awk -F'[= ."]' '/VERSION_ID/{print $3}' /etc/os-release)
fi
if [[ -z "$os_version" && -f /etc/lsb-release ]]; then
    os_version=$(awk -F'[= ."]+' '/DISTRIB_RELEASE/{print $2}' /etc/lsb-release)
fi

if [[ x"${release}" == x"centos" ]]; then
    if [[ ${os_version} -le 6 ]]; then
        echo -e "${red}请使用 CentOS 7 或更高版本的系统！${plain}\n" && exit 1
    fi
elif [[ x"${release}" == x"ubuntu" ]]; then
    if [[ ${os_version} -lt 16 ]]; then
        echo -e "${red}请使用 Ubuntu 16 或更高版本的系统！${plain}\n" && exit 1
    fi
elif [[ x"${release}" == x"debian" ]]; then
    if [[ ${os_version} -lt 8 ]]; then
        echo -e "${red}请使用 Debian 8 或更高版本的系统！${plain}\n" && exit 1
    fi
fi
install_base() {
    if [[ x"${release}" == x"centos" ]]; then
        yum install epel-release -y
        yum install wget curl unzip tar crontabs socat -y
    else
        apt update -y
        apt install wget curl unzip tar cron socat -y
    fi
}
# 0: running, 1: not running, 2: not installed
check_status() {
    if [[ ! -f /lib/systemd/system/docker.service ]]; then
        return 2
    fi
    temp=$(systemctl status docker | grep Active | awk '{print $3}' | cut -d "(" -f2 | cut -d ")" -f1)
    if [[ x"${temp}" == x"running" ]]; then
        return 0
    else
        return 1
    fi
}
install_docker() {
    curl -fsSL https://get.docker.com | sh
}
display_config(){
    echo -e "${Info} 服务器配置:"
    if [[ -e ${config_platform_file} ]]; then
        cat ${config_platform_file}
    else
        echo -e "${red}服务器配置文件不存在${plain}"
    fi
    # echo -e "${Info} 设备配置:"
    # if [[ -d ${config_device_file} ]]; then
    #     cat ${config_device_file}
    # else
    #     echo -e "${red}设备配置文件不存在${plain}"
    # fi
}
chech_docker(){
    systemctl is-active --quiet docker
}
Get_IP(){
	ip=$(wget -qO- -t1 -T2 ipinfo.io/ip)
	if [[ -z "${ip}" ]]; then
		ip=$(wget -qO- -t1 -T2 api.ip.sb/ip)
		if [[ -z "${ip}" ]]; then
			ip=$(wget -qO- -t1 -T2 members.3322.org/dyndns/getip)
			if [[ -z "${ip}" ]]; then
				ip="VPS_IP"
			fi
		fi
	fi
}
Set_server_pub_addr(){
	addr=$1
	if [[ "${addr}" == "Modify" ]]; then
		server_pub_addr=$(cat ${config_platform_file} | grep "serverip = " | awk -F "[\\\"]" '{print $2}')
		if [[ -z ${server_pub_addr} ]]; then
			echo -e "${Error} 获取当前配置的 服务器IP或域名失败！" && exit 1
		else
			echo -e "${Info} 当前配置的服务器IP或域名为： ${Green_font_prefix}${server_pub_addr}${Font_color_suffix}"
		fi
	fi
	echo "请输入用户配置中要显示的 服务器IP或域名 (当服务器有多个IP时，可以指定用户配置中显示的IP或者域名)"
	read -e -p "(默认自动检测外网IP):" PLATFORMIP
	if [[ -z "${PLATFORMIP}" ]]; then
		Get_IP
		if [[ ${ip} == "VPS_IP" ]]; then
			while true
			do
			read -e -p "${Error} 自动检测外网IP失败，请手动输入服务器IP或域名" PLATFORMIP
			if [[ -z "$PLATFORMIP" ]]; then
				echo -e "${Error} 不能为空！"
			else
				break
			fi
			done
		else
			PLATFORMIP="${ip}"
		fi
	fi
	echo && echo ${Separator_1} && echo -e "	IP或域名 : ${Green_font_prefix}${PLATFORMIP}${Font_color_suffix}" && echo ${Separator_1} && echo
}
Set_container_mode(){
    while true
    do
    read -e -p "请输入容器网络模式：(host/bridge)：" networkmode
    if [[ -z "$networkmode" ]]; then
        echo -e "${Error} 不能为空！"
    else
        if [[ ${networkmode} == "host" ]]; then
            break
        elif [[ ${networkmode} == "bridge" ]]; then
            break
        else
            echo -e "${Error} 输入错误(host/bridge 二选一)！"
        fi
    fi
    done
    echo && echo ${Separator_1} && echo -e "	容器网络模式 : ${Green_font_prefix}${networkmode}${Font_color_suffix}" && echo ${Separator_1} && echo
}

Choose_default_mode(){
    read -e -p "是否使用默认配置：(Y/n)：" default
    if [[ -z "$default" ]]; then
        default="Y"
    else
        if [[ ${default} == "Y" ]]; then
            echo -e "${Info} 选择默认配置！"
        elif [[ ${default} == "y" ]]; then
            echo -e "${Info} 选择默认配置！"
        else
            echo -e "${Info} 自定义端口配置！"
            default="N"
        fi
    fi
}

Set_config_webport(){
	while true
	do
	echo -e "请输入要设置的Web 端口"
	read -e -p "(默认: 82):" WEBPORT
	[[ -z "$WEBPORT" ]] && WEBPORT="82"
	echo $((${WEBPORT}+0)) &>/dev/null
	if [[ $? == 0 ]]; then
		if [[ ${WEBPORT} -ge 1 ]] && [[ ${WEBPORT} -le 65535 ]]; then
			echo && echo ${Separator_1} && echo -e "	端口 : ${Green_font_prefix}${WEBPORT}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} 请输入正确的数字(1-65535)"
		fi
	else
		echo -e "${Error} 请输入正确的数字(1-65535)"
	fi
	done
}

Set_config_klnkport(){
	while true
	do
	echo -e "请输入要设置的KLNK 端口"
	read -e -p "(默认: 60000):" KLNKPORT
	[[ -z "$KLNKPORT" ]] && KLNKPORT="60000"
	echo $((${KLNKPORT}+0)) &>/dev/null
	if [[ $? == 0 ]]; then
		if [[ ${KLNKPORT} -ge 1 ]] && [[ ${KLNKPORT} -le 65535 ]]; then
			echo && echo ${Separator_1} && echo -e "	端口 : ${Green_font_prefix}${KLNKPORT}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} 请输入正确的数字(1-65535)"
		fi
	else
		echo -e "${Error} 请输入正确的数字(1-65535)"
	fi
	done
}

Set_config_fwdport(){
	while true
	do
	echo -e "请输入要设置的KLNK转发 端口"
	read -e -p "(默认: 60001):" KLNKFWDPORT
	[[ -z "$KLNKFWDPORT" ]] && KLNKFWDPORT="60001"
	echo $((${KLNKFWDPORT}+0)) &>/dev/null
	if [[ $? == 0 ]]; then
		if [[ ${KLNKFWDPORT} -ge 1 ]] && [[ ${KLNKFWDPORT} -le 65535 ]]; then
			echo && echo ${Separator_1} && echo -e "	端口 : ${Green_font_prefix}${KLNKFWDPORT}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} 请输入正确的数字(1-65535)"
		fi
	else
		echo -e "${Error} 请输入正确的数字(1-65535)"
	fi
	done
}

Set_config_fwdmin(){
	while true
	do
	echo -e "请输入要设置的转发/流服务 起始端口"
	read -e -p "(默认: 30000):" FWDMIN
	[[ -z "$FWDMIN" ]] && FWDMIN="30000"
	echo $((${FWDMIN}+0)) &>/dev/null
	if [[ $? == 0 ]]; then
		if [[ ${FWDMIN} -ge 1 ]] && [[ ${FWDMIN} -le 65535 ]]; then
			echo && echo ${Separator_1} && echo -e "	端口 : ${Green_font_prefix}${FWDMIN}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} 请输入正确的数字(1-65535)"
		fi
	else
		echo -e "${Error} 请输入正确的数字(1-65535)"
	fi
	done
}

Set_config_fwdmax(){
	while true
	do
	echo -e "请输入要设置的转发/流服务 结束端口"
	read -e -p "(默认: 30050):" FWDMAX
	[[ -z "$FWDMAX" ]] && FWDMAX="30050"
	echo $((${FWDMAX}+0)) &>/dev/null
	if [[ $? == 0 ]]; then
		if [[ ${FWDMAX} -ge 1 ]] && [[ ${FWDMAX} -le 65535 ]]; then
			echo && echo ${Separator_1} && echo -e "	端口 : ${Green_font_prefix}${FWDMAX}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} 请输入正确的数字(1-65535)"
		fi
	else
		echo -e "${Error} 请输入正确的数字(1-65535)"
	fi
	done
}

Set_config_tunmin(){
	while true
	do
	echo -e "请输入要设置的Coturn 转发服务 最小端口"
	read -e -p "(默认: 5000):" TUNMIN
	[[ -z "$TUNMIN" ]] && TUNMIN="5000"
	echo $((${TUNMIN}+0)) &>/dev/null
	if [[ $? == 0 ]]; then
		if [[ ${TUNMIN} -ge 1 ]] && [[ ${TUNMIN} -le 65535 ]]; then
			echo && echo ${Separator_1} && echo -e "	端口 : ${Green_font_prefix}${TUNMIN}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} 请输入正确的数字(1-65535)"
		fi
	else
		echo -e "${Error} 请输入正确的数字(1-65535)"
	fi
	done
}

Set_config_tunmax(){
	while true
	do
	echo -e "请输入要设置的Coturn 转发服务 最大端口"
	read -e -p "(默认: 5100):" TUNMAX
	[[ -z "$TUNMAX" ]] && TUNMAX="5100"
	echo $((${TUNMAX}+0)) &>/dev/null
	if [[ $? == 0 ]]; then
		if [[ ${TUNMAX} -ge 1 ]] && [[ ${TUNMAX} -le 65535 ]]; then
			echo && echo ${Separator_1} && echo -e "	端口 : ${Green_font_prefix}${TUNMAX}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} 请输入正确的数字(1-65535)"
		fi
	else
		echo -e "${Error} 请输入正确的数字(1-65535)"
	fi
	done
}

Set_config_tunport(){
	while true
	do
	echo -e "请输入要设置的Coturn 服务监听端口"
	read -e -p "(默认: 3478):" TUNPORT
	[[ -z "$TUNPORT" ]] && TUNPORT="3478"
	echo $((${TUNPORT}+0)) &>/dev/null
	if [[ $? == 0 ]]; then
		if [[ ${TUNPORT} -ge 1 ]] && [[ ${TUNPORT} -le 65535 ]]; then
			echo && echo ${Separator_1} && echo -e "	端口 : ${Green_font_prefix}${TUNPORT}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} 请输入正确的数字(1-65535)"
		fi
	else
		echo -e "${Error} 请输入正确的数字(1-65535)"
	fi
	done
}
Set_config_tunuser(){
	echo "请输入要设置的TUN服务器 用户名(不支持中文、空格, 会报错 !)"
	read -e -p "(默认: admin):" TUNUSER
	[[ -z "${TUNUSER}" ]] && TUNUSER="admin"
	TUNUSER=$(echo "${TUNUSER}"|sed 's/ //g')
	echo && echo ${Separator_1} && echo -e "	TUN用户名 : ${Green_font_prefix}${TUNUSER}${Font_color_suffix}" && echo ${Separator_1} && echo
}
Set_config_tunpassword(){
	echo "请输入要设置的TUN服务器 密码"
	read -e -p "(默认: kiloview123456):" TUNPASS
	[[ -z "${TUNPASS}" ]] && TUNPASS="kiloview123456"
	echo && echo ${Separator_1} && echo -e "	TUN密码 : ${Green_font_prefix}${TUNPASS}${Font_color_suffix}" && echo ${Separator_1} && echo
}
Set_config_tunrealm(){
	echo "请输入要设置的TUN服务器 TUNREALM"
	read -e -p "(默认: demo):" TUNREALM
	[[ -z "${TUNREALM}" ]] && TUNREALM="demo"
	echo && echo ${Separator_1} && echo -e "	TUN REALM : ${Green_font_prefix}${TUNREALM}${Font_color_suffix}" && echo ${Separator_1} && echo
}
Set_config_all(){
	lal=$1
	if [[ "${lal}" == "Modify" ]]; then
		Set_config_webport
        Set_config_klnkport
        Set_config_fwdport
        Set_config_fwdmin
        Set_config_fwdmax
        Set_config_tunmin
        Set_config_tunmax
        Set_config_tunport
		Set_config_tunuser
        Set_config_tunpassword
        Set_config_tunrealm
	else
        if [[ ${networkmode} == "host" ]]; then
            WEBPORT="82"
        else
            Set_config_webport
        fi
        Set_config_klnkport
        Set_config_fwdport
        Set_config_fwdmin
        Set_config_fwdmax
        Set_config_tunmin
        Set_config_tunmax
        Set_config_tunport
		Set_config_tunuser
        Set_config_tunpassword
        Set_config_tunrealm
	fi
}
showconf(){
    echo -e "----------------------------------------"
    echo -e "Web 端口：${WEBPORT} TCP"
    echo -e "聚合平台IP：${PLATFORMIP}"
    echo -e "聚合工作端口：${KLNKPORT} UDP"
    echo -e "聚合转发服务端口：${KLNKFWDPORT} UDP"
    echo -e "转发/流服务最小端口：${FWDMIN} TCP+UDP"
    echo -e "转发/流服务最大端口：${FWDMAX} TCP+UDP"
    echo -e "TUN服务器工作最小端口：${TUNMIN} TCP+UDP"
    echo -e "TUN服务器工作最大端口：${TUNMAX} TCP+UDP"
    echo -e "TUN服务器端口：${TUNPORT} + $((${TUNPORT}+1)) TCP+UDP"
    echo -e "TUN服务器用户名：${TUNUSER}"
    echo -e "TUN服务器密码：${TUNPASS}"
    echo -e "TUN服务器REALM：${TUNREALM}"
    echo -e "----------------------------------------"
}
GetEnv(){
    envarg=$1
    # echo -e ${envarg}
    format='{{range $index, $value := .Config.Env}}{{if eq (index (split $value "=") 0) "'$envarg'" }}{{range $i, $part := (split $value "=")}}{{if gt $i 1}}{{print "="}}{{end}}{{if gt $i 0}}{{print $part}}{{end}}{{end}}{{end}}{{end}}'
    # echo -e $format
    ENV=`docker inspect -f "$format" klnkserver`
    if [[ -z $ENV ]]; then
        # echo -e "${Error} 获取 $envarg 参数失败！"
        return 1
    else
        return 0
    fi
}
Run_container(){    
    if [[ ${networkmode} == "host" ]]; then
        cmd="docker create --restart=always --name klnkserver \
            -e WEBPORT=$WEBPORT \
            -e PLATFORMIP=$PLATFORMIP \
            -e KLNKPORT=$KLNKPORT \
            -e KLNKFWDPORT=$KLNKFWDPORT \
            -e FWDMIN=$FWDMIN \
            -e FWDMAX=$FWDMAX \
            -e TUNMIN=$TUNMIN \
            -e TUNMAX=$TUNMAX \
            -e TUNPORT=$TUNPORT \
            -e TUNUSER=$TUNUSER \
            -e TUNPASS=$TUNPASS \
            -e TUNREALM=$TUNREALM \
            -v /data:/data \
            --privileged --user root \
            --network host \
            kiloview/klnkserver"
    elif [[ ${networkmode} == "bridge" ]]; then
        cmd="docker create --restart=always --name klnkserver \
            -p $WEBPORT:82 \
            -p $KLNKPORT:$KLNKPORT/udp \
            -p $KLNKFWDPORT:$KLNKFWDPORT/udp \
            -p $FWDMIN-$FWDMAX:$FWDMIN-$FWDMAX \
            -p $FWDMIN-$FWDMAX:$FWDMIN-$FWDMAX/udp \
            -p $TUNPORT-$((${TUNPORT}+1)):$TUNPORT-$((${TUNPORT}+1)) \
            -p $TUNPORT-$((${TUNPORT}+1)):$TUNPORT-$((${TUNPORT}+1))/udp \
            -p $TUNMIN-$TUNMAX:$TUNMIN-$TUNMAX/udp \
            -e WEBPORT=$WEBPORT \
            -e PLATFORMIP=$PLATFORMIP \
            -e KLNKPORT=$KLNKPORT \
            -e KLNKFWDPORT=$KLNKFWDPORT \
            -e FWDMIN=$FWDMIN \
            -e FWDMAX=$FWDMAX \
            -e TUNMIN=$TUNMIN \
            -e TUNMAX=$TUNMAX \
            -e TUNPORT=$TUNPORT \
            -e TUNUSER=$TUNUSER \
            -e TUNPASS=$TUNPASS \
            -e TUNREALM=$TUNREALM \
            -v /data:/data \
            --privileged --user root \
            kiloview/klnkserver"
    else
        echo -e "${Error} 输入错误(host/bridge 二选一)！"
    fi
    eval ${cmd}
    if [[ $? == 0 ]]; then
        echo -e "${Info} 创建容器成功"
    else
        echo -e "${Error} 创建容器失败！" && exit 1
        # 删除已创建的容器
        # docker rm -f klnkserver &> /dev/null
    fi

    docker start klnkserver
    if [[ $? == 0 ]]; then
        echo -e "${Info} 运行容器成功"
    else
        echo -e "${Error} 运行容器失败！" && exit 1
        # 删除已创建的容器
        # docker rm -f klnkserver &> /dev/null
    fi
}
Set_default_config(){
    WEBPORT="82"
    KLNKPORT="60000"
    KLNKFWDPORT="60001"
    FWDMIN="30000"
    FWDMAX="30050"
    TUNMIN="5000"
    TUNMAX="5100"
    TUNPORT="3478"
    TUNUSER="admin"
    TUNPASS="kiloview123456"
    TUNREALM="demo"
}
install_klnkserver() {
    docker inspect klnkserver -f '{{.Name}}' &> /dev/null
    if [ $? -eq 0 ] ;then
        echo -e "${Error} 容器已创建，如需安装请先卸载！" && exit 1
    fi

    echo -e "${green}开始安装${plain}"
    #install_base

    if [[ -d /data ]]; then
        echo -e "${red}/data/目录已存在${plain}"
    else
        mkdir /data -p
    fi

    echo -e "${Info} 开始设置 容器运行方式..."
	Set_container_mode
	echo -e "${Info} 开始设置 服务器公网IP（设备连接）..."
	Set_server_pub_addr
    Choose_default_mode
    if [[ ${default} == "Y" ]] || [[ ${default} == "y" ]]; then
	    Set_default_config
    else
        Set_config_all
    fi
    showconf

    #删除网页
    if [[ -d /data/web ]]; then
	rm -rf /data/web
    fi
    #删除程序
    if [[ -d /data/shine ]]; then
	rm -rf /data/shine
    fi
    #拉取最新版本镜像
    echo -e "${Info} 拉取最新版本 kiloview/klnkserver 镜像..."
    docker pull kiloview/klnkserver
    if [[ $? -ne 0 ]]; then
	    echo -e "${Error} 拉取最新版本镜像失败！" && exit 1
    fi
    Run_container
    # display_config
    # echo -e ""
    # echo "KlnkServer 管理脚本使用方法: "
    # echo "------------------------------------------"
    # echo "KlnkServer                    - 显示管理菜单 (功能更多)"
    # echo "KlnkServer start              - 启动 KlnkServer"
    # echo "KlnkServer stop               - 停止 KlnkServer"
    # echo "KlnkServer restart            - 重启 KlnkServer"
    # echo "KlnkServer status             - 查看 KlnkServer 状态"
    # echo "KlnkServer log                - 查看 KlnkServer 日志"
    # echo "KlnkServer update             - 更新 KlnkServer"
    # echo "KlnkServer config             - 显示配置文件内容"
    # echo "KlnkServer install            - 安装 KlnkServer"
    # echo "KlnkServer uninstall          - 卸载 KlnkServer"
    # echo "KlnkServer version            - 查看 KlnkServer 版本"
    # echo "------------------------------------------"
}
menu_status(){
	if [[ -d /data ]] && [[ -e $config_platform_file ]]; then
        docker inspect klnkserver -f '{{.Name}}' &> /dev/null
        if [ $? -eq 0 ] ;then
            if [ "$( docker container inspect -f '{{.State.Running}}' klnkserver )" == "true" ]; then
                echo -e " 当前状态: ${Green_font_prefix}已安装${Font_color_suffix} 并 ${Green_font_prefix}已启动${Font_color_suffix}"
            else
                echo -e " 当前状态: ${Green_font_prefix}已安装${Font_color_suffix} 但 ${Red_font_prefix}未启动${Font_color_suffix}"
            fi
        else
            echo -e "${red}KlnkServer 容器未创建！${plain}"
        fi
		cd "/data"
	else
		echo -e " 当前状态: ${Red_font_prefix}未安装${Font_color_suffix}"
	fi
}

log_klnkserver(){
    if [ "$( docker container inspect -f '{{.State.Running}}' klnkserver )" == "true" ]; then
        echo -e " ${Green_font_prefix}服务器未启动${Font_color_suffix}"
    else
        docker exec -it klnkserver tail -f /var/log/klnkserver.log
    fi    
}

uninstall_klnkserver(){
    docker inspect klnkserver -f '{{.Name}}' &> /dev/null
    if [ $? -ne 0 ] ;then
        echo -e "${Error} 容器未创建！" && exit 1
    fi

    docker rm -f klnkserver &> /dev/null
    if [[ $? == 0 ]]; then
        echo -e "${green}删除容器成功${plain}"
    else
        echo -e "${red}删除容器失败${plain}"
    fi

    # apt autoremove docker-ce
    # if [[ $? == 0 ]]; then
    #     echo -e "${green}卸载docker成功${plain}"
    # else
    #     echo -e "${red}卸载docker失败${plain}"
    # fi

    if [[ -e ${config_platform_file} ]]; then
        rm -rf ${config_platform_file}
    fi
}

update_klnkserver(){
    docker inspect klnkserver -f '{{.Name}}' &> /dev/null
    if [ $? -ne 0 ] ;then
        echo -e "${Error} 容器未创建，无法升级！" && exit 1
    fi

    docker container inspect -f '{{.NetworkSettings.Networks}}' klnkserver | grep host &> /dev/null
    if [[ $? == 0 ]]; then
        networkmode="host"
    fi
    
    docker container inspect -f '{{.NetworkSettings.Networks}}' klnkserver | grep bridge &> /dev/null
    if [[ $? == 0 ]]; then
        networkmode="bridge"
    fi

    if [[ -z "$networkmode" ]]; then
        echo -e "${Error} 网络模式获取失败！" && exit 1
    fi

    GetEnv "WEBPORT"
    if [[ $? == 0 ]]; then
        WEBPORT=$ENV
    else
        echo -e "${Error} WEBPORT 参数获取失败！" && exit 1
    fi

    GetEnv "PLATFORMIP"
    if [[ $? == 0 ]]; then
        PLATFORMIP=$ENV
    else
        echo -e "${Error} PLATFORMIP 参数获取失败！" && exit 1
    fi

    GetEnv "KLNKPORT"
    if [[ $? == 0 ]]; then
        KLNKPORT=$ENV
    else
        echo -e "${Error} KLNKPORT 参数获取失败！" && exit 1
    fi

    GetEnv "KLNKFWDPORT"
    if [[ $? == 0 ]]; then
        KLNKFWDPORT=$ENV
    else
        echo -e "${Error} KLNKFWDPORT 参数获取失败！" && exit 1
    fi

    GetEnv "FWDMIN"
    if [[ $? == 0 ]]; then
        FWDMIN=$ENV
    else
        echo -e "${Error} FWDMIN 参数获取失败！" && exit 1
    fi

    GetEnv "FWDMAX"
    if [[ $? == 0 ]]; then
        FWDMAX=$ENV
    else
        echo -e "${Error} FWDMAX 参数获取失败！" && exit 1
    fi

    GetEnv "TUNMIN"
    if [[ $? == 0 ]]; then
        TUNMIN=$ENV
    else
        echo -e "${Error} TUNMIN 参数获取失败！" && exit 1
    fi

    GetEnv "TUNMAX"
    if [[ $? == 0 ]]; then
        TUNMAX=$ENV
    else
        echo -e "${Error} TUNMAX 参数获取失败！" && exit 1
    fi

    GetEnv "TUNPORT"
    if [[ $? == 0 ]]; then
        TUNPORT=$ENV
    else
        echo -e "${Error} TUNPORT 参数获取失败！" && exit 1
    fi

    GetEnv "TUNUSER"
    if [[ $? == 0 ]]; then
        TUNUSER=$ENV
    else
        echo -e "${Error} TUNUSER 参数获取失败！" && exit 1
    fi

    GetEnv "TUNPASS"
    if [[ $? == 0 ]]; then
        TUNPASS=$ENV
    else
        echo -e "${Error} TUNPASS 参数获取失败！" && exit 1
    fi

    GetEnv "TUNREALM"
    if [[ $? == 0 ]]; then
        TUNREALM=$ENV
    else
        echo -e "${Error} TUNREALM 参数获取失败！" && exit 1
    fi

    #删除网页
    if [[ -d /data/web ]]; then
        rm -rf /data/web
    fi

    #删除程序
    if [[ -d /data/shine ]]; then
        rm -rf /data/shine
    fi

    #拉取最新版本镜像
    echo -e "${Info} 拉取最新版本 kiloview/klnkserver 镜像..."
    docker pull kiloview/klnkserver
    if [[ $? -ne 0 ]]; then
        echo -e "${Error} 拉取最新版本镜像失败！" && exit 1
    fi

    echo -e "${Info} 删除旧容器..."
    docker rm -f klnkserver

    echo -e "${Info} 重新运行镜像..."
    Run_container
}

# [[ ${release} != "ubuntu" ]] && echo -e "${Error} 本脚本不支持当前系统 ${release} !" && exit 1
check_status
if [[ $? == 0 ]]; then
    echo -e "${green}Docker 运行中${plain}"
    echo -e ""
elif [[ $? == 2 ]]; then
    echo -e "${red}Docker服务 未安装，一键安装docker: ${plain}"
    echo -e "${red}curl -fsSL https://get.docker.com | sh${plain}" && exit 1
else
    echo -e "${red}Docker服务 已安装，但未启动。尝试启动...${plain}"
    systemctl start docker
    if [[ $? == 0 ]]; then
        echo -e "${green}Docker服务 启动成功${plain}"
    else
        echo -e "${green}Docker服务 启动失败${plain}" && exit 1
    fi
fi

action=$1
if [[ "${action}" == "config" ]]; then
	display_config
elif [[ "${action}" == "log" ]]; then
	log_klnkserver
else
	echo -e "  Kiloview KlnkServer 一键管理脚本 ${Red_font_prefix}[v${sh_ver}]${Font_color_suffix}
  ${Green_font_prefix}1.${Font_color_suffix} 安装 KlnkServer
  ${Green_font_prefix}2.${Font_color_suffix} 更新 KlnkServer
  ${Green_font_prefix}3.${Font_color_suffix} 卸载 KlnkServer
  "
	menu_status
	echo && read -e -p "请输入数字 [1-3]：" num
case "$num" in
	1)
	install_klnkserver
	;;
	2)
	update_klnkserver
	;;
	3)
	uninstall_klnkserver
	;;
	*)
	echo -e "${Error} 请输入正确的数字 [1-3]"
	;;
esac
fi
