#!/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}[Information]${Font_color_suffix}"
Error="${Red_font_prefix}[Error]${Font_color_suffix}"
Tip="${Green_font_prefix}[Tip]${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}error：${plain} You must run this script with root user\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}Detection schema failed, using the default schema: ${arch}${plain}"
fi

# echo "schema: ${arch}"

if [ "$(getconf WORD_BIT)" != '32' ] && [ "$(getconf LONG_BIT)" != '64' ] ; then
    echo "This software doesn't support 32-bit system(x86)，please use 64-bit operating system(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}Please use CentOS 7 or higher system.${plain}\n" && exit 1
    fi
elif [[ x"${release}" == x"ubuntu" ]]; then
    if [[ ${os_version} -lt 16 ]]; then
        echo -e "${red}Please use Ubuntu 16 or higher system.${plain}\n" && exit 1
    fi
elif [[ x"${release}" == x"debian" ]]; then
    if [[ ${os_version} -lt 8 ]]; then
        echo -e "${red}Please use Debian 8 or higher system.${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} Server configuration:"
    if [[ -e ${config_platform_file} ]]; then
        cat ${config_platform_file}
    else
        echo -e "${red}The file of server configuration does not exist${plain}"
    fi
    # echo -e "${Info} Setting configuration:"
    # if [[ -d ${config_device_file} ]]; then
    #     cat ${config_device_file}
    # else
    #     echo -e "${red}The file of setting configuration does not exist${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} Failed to obtain currently configured server IP and domain name" && exit 1
		else
			echo -e "${Info} Currently configured server IP and domain name： ${Green_font_prefix}${server_pub_addr}${Font_color_suffix}"
		fi
	fi
	echo "Enter the server IP or domain name to display in the user configuration (when the server has multiple IP, you can specify the IP or domain name displayed in the user configuration)"
	read -e -p "(The platform IP is automatically detected by default):" PLATFORMIP
	if [[ -z "${PLATFORMIP}" ]]; then
		Get_IP
		if [[ ${ip} == "VPS_IP" ]]; then
			while true
			do
			read -e -p "${Error} Failed to detect platform IP automatically, please manually enter server IP and domain name" PLATFORMIP
			if [[ -z "$PLATFORMIP" ]]; then
				echo -e "${Error} Cannot be empty"
			else
				break
			fi
			done
		else
			PLATFORMIP="${ip}"
		fi
	fi
	echo && echo ${Separator_1} && echo -e "	IP or domain name : ${Green_font_prefix}${PLATFORMIP}${Font_color_suffix}" && echo ${Separator_1} && echo
}
Set_container_mode(){
    while true
    do
    read -e -p "please enter container network mode：(host/bridge)：" networkmode
    if [[ -z "$networkmode" ]]; then
        echo -e "${Error} Cannot be empty"
    else
        if [[ ${networkmode} == "host" ]]; then
            break
        elif [[ ${networkmode} == "bridge" ]]; then
            break
        else
            echo -e "${Error} Error input(either host or bridge )！"
        fi
    fi
    done
    echo && echo ${Separator_1} && echo -e "	Container network mode : ${Green_font_prefix}${networkmode}${Font_color_suffix}" && echo ${Separator_1} && echo
}

Choose_default_mode(){
    read -e -p "If to use default configuration：(Y/n)：" default
    if [[ -z "$default" ]]; then
        default="Y"
    else
        if [[ ${default} == "Y" ]]; then
            echo -e "${Info} Select configuration by default"
        elif [[ ${default} == "y" ]]; then
            echo -e "${Info} Select configuration by default "
        else
            echo -e "${Info} Customize the port configuration"
            default="N"
        fi
    fi
}

Set_config_webport(){
	while true
	do
	echo -e "Enter the Web port to set up"
	read -e -p "(Default: 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 "	Port : ${Green_font_prefix}${WEBPORT}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} Enter the correct number(1-65535)"
		fi
	else
		echo -e "${Error} Enter the correct number(1-65535)"
	fi
	done
}

Set_config_klnkport(){
	while true
	do
	echo -e "Enter the KLNK port to set up"
	read -e -p "(Default: 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 "	Port : ${Green_font_prefix}${KLNKPORT}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} Enter the correct number(1-65535)"
		fi
	else
		echo -e "${Error} Enter the correct number(1-65535)"
	fi
	done
}

Set_config_fwdport(){
	while true
	do
	echo -e "Enter the KLNK forwarding port to set up"
	read -e -p "(Default: 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 "	Port : ${Green_font_prefix}${KLNKFWDPORT}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} Enter the correct number(1-65535)"
		fi
	else
		echo -e "${Error} Enter the correct number(1-65535)"
	fi
	done
}

Set_config_fwdmin(){
	while true
	do
	echo -e "Enter the forward / streaming service start port to set up"
	read -e -p "(Default: 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 "	Port : ${Green_font_prefix}${FWDMIN}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} Enter the correct number(1-65535)"
		fi
	else
		echo -e "${Error} Enter the correct number(1-65535)"
	fi
	done
}

Set_config_fwdmax(){
	while true
	do
	echo -e "Enter the forward / streaming service end port to set up"
	read -e -p "(Default: 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 "	Port : ${Green_font_prefix}${FWDMAX}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} Enter the correct number(1-65535)"
		fi
	else
		echo -e "${Error} Enter the correct number(1-65535)"
	fi
	done
}

Set_config_tunmin(){
	while true
	do
	echo -e "Enter the Coturn forwarding service minimum port to set up"
	read -e -p "(Default: 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 "	Port : ${Green_font_prefix}${TUNMIN}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} Enter the correct number(1-65535)"
		fi
	else
		echo -e "${Error} Enter the correct number(1-65535)"
	fi
	done
}

Set_config_tunmax(){
	while true
	do
	echo -e "Enter the Coturn forwarding service maximum port to set up"
	read -e -p "(Default: 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 "	Port : ${Green_font_prefix}${TUNMAX}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} Enter the correct number(1-65535)"
		fi
	else
		echo -e "${Error} Enter the correct number(1-65535)"
	fi
	done
}

Set_config_tunport(){
	while true
	do
	echo -e "Enter the Coturn service listening port to set up"
	read -e -p "(Default: 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 "	Port : ${Green_font_prefix}${TUNPORT}${Font_color_suffix}" && echo ${Separator_1} && echo
			break
		else
			echo -e "${Error} Enter the correct number(1-65535)"
		fi
	else
		echo -e "${Error} Enter the correct number(1-65535)"
	fi
	done
}
Set_config_tunuser(){
	echo "Enter the TUN server username to set (Not support Chinese and space. Error!)"
	read -e -p "(Default: admin):" TUNUSER
	[[ -z "${TUNUSER}" ]] && TUNUSER="admin"
	TUNUSER=$(echo "${TUNUSER}"|sed 's/ //g')
	echo && echo ${Separator_1} && echo -e "	TUN username : ${Green_font_prefix}${TUNUSER}${Font_color_suffix}" && echo ${Separator_1} && echo
}
Set_config_tunpassword(){
	echo "Enter the TUN server password to set up"
	read -e -p "(Default: kiloview123456):" TUNPASS
	[[ -z "${TUNPASS}" ]] && TUNPASS="kiloview123456"
	echo && echo ${Separator_1} && echo -e "	TUN password : ${Green_font_prefix}${TUNPASS}${Font_color_suffix}" && echo ${Separator_1} && echo
}
Set_config_tunrealm(){
	echo "Enter the TUNREALM server to set up"
	read -e -p "(Default: 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 port: ${WEBPORT} TCP"
    echo -e "Kilolink platform IP: ${PLATFORMIP}"
    echo -e "Kilolink working port: ${KLNKPORT} UDP"
    echo -e "Kilolink forwarding server port: ${KLNKFWDPORT} UDP"
    echo -e "Forward /stream service minimum port: ${FWDMIN} TCP+UDP"
    echo -e "Forward /stream service maximum port: ${FWDMAX} TCP+UDP"
    echo -e "The TUN server working minimum port: ${TUNMIN} TCP+UDP"
    echo -e "The TUN server working the maximum port TUN: ${TUNMAX} TCP+UDP"
    echo -e "TUN server port: ${TUNPORT} + $((${TUNPORT}+1)) TCP+UDP"
    echo -e "TUN server username: ${TUNUSER}"
    echo -e "TUN server password: ${TUNPASS}"
    echo -e "TUN server 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} Failed to obtain $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} Error input (either host or bridge )！"
    fi
    eval ${cmd}
    if [[ $? == 0 ]]; then
        echo -e "${Info} Success to create container"
    else
        echo -e "${Error} Failed to create container" && exit 1
        # Delete the container created
        # docker rm -f klnkserver &> /dev/null
    fi

    docker start klnkserver
    if [[ $? == 0 ]]; then
        echo -e "${Info} Success to run container"
    else
        echo -e "${Error} Failed to run container" && exit 1
        # Delete the container created
        # 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} The container has been created, please uninstall before install" && exit 1
    fi

    echo -e "${green} Start installing${plain}"
    #install_base

    if [[ -d /data ]]; then
        echo -e "${red}/data/The directory already exists${plain}"
    else
        mkdir /data -p
    fi

    echo -e "${Info} Start setting the container mode..."
	Set_container_mode
	echo -e "${Info} Start Setting up the Server Public Network IP (Device connection)..."
	Set_server_pub_addr
    Choose_default_mode
    if [[ ${default} == "Y" ]] || [[ ${default} == "y" ]]; then
	    Set_default_config
    else
        Set_config_all
    fi
    showconf

    #Delete web
    if [[ -d /data/web ]]; then
	rm -rf /data/web
    fi
    #Delete program
    if [[ -d /data/shine ]]; then
	rm -rf /data/shine
    fi
    #Pull up the latest version of the mirror
    echo -e "${Info} Pull up the latest version of kiloview/klnkserver mirror..."
    docker pull kiloview/klnkserver
    if [[ $? -ne 0 ]]; then
	    echo -e "${Error} Failed to pull up the latest mirror version" && exit 1
    fi
    Run_container
    # display_config
    # echo -e ""
    # echo "KlnkServer Managing the script usage method "
    # echo "------------------------------------------"
    # echo "KlnkServer                    -Display the management menu (more functions) "
    # echo "KlnkServer start              - Start KlnkServer"
    # echo "KlnkServer stop               - Stop KlnkServer"
    # echo "KlnkServer restart            - Restart KlnkServer"
    # echo "KlnkServer status             - Check KlnkServer status"
    # echo "KlnkServer log                - Check KlnkServer log"
    # echo "KlnkServer update             - Update KlnkServer"
    # echo "KlnkServer config             - Display the contents of configured file"
    # echo "KlnkServer install            - Install KlnkServer"
    # echo "KlnkServer uninstall          - Uninstall KlnkServer"
    # echo "KlnkServer version            - Check KlnkServer version"
    # 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 " Current status: ${Green_font_prefix}Installed${Font_color_suffix} and ${Green_font_prefix}Started${Font_color_suffix}"
            else
                echo -e " Current status: ${Green_font_prefix}Installed${Font_color_suffix} but ${Red_font_prefix}Not started${Font_color_suffix}"
            fi
        else
            echo -e "${red}KlnkServer The container was not created${plain}"
        fi
		cd "/data"
	else
		echo -e " Current status: ${Red_font_prefix}Not installed${Font_color_suffix}"
	fi
}

log_klnkserver(){
    if [ "$( docker container inspect -f '{{.State.Running}}' klnkserver )" == "true" ]; then
        echo -e " ${Green_font_prefix}The server is not started${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} The container was not created" && exit 1
    fi

    docker rm -f klnkserver &> /dev/null
    if [[ $? == 0 ]]; then
        echo -e "${green}Success to delete container${plain}"
    else
        echo -e "${red}Failed to delete container${plain}"
    fi

    # apt autoremove docker-ce
    # if [[ $? == 0 ]]; then
    #     echo -e "${green}Success to uninstall docker${plain}"
    # else
    #     echo -e "${red}Failed to uninstall 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} The container was not created and cannot be upgraded" && 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} Failed to obtain network mode" && exit 1
    fi

    GetEnv "WEBPORT"
    if [[ $? == 0 ]]; then
        WEBPORT=$ENV
    else
        echo -e "${Error} Failed to obtain webport parameters WEBPORT " && exit 1
    fi

    GetEnv "PLATFORMIP"
    if [[ $? == 0 ]]; then
        PLATFORMIP=$ENV
    else
        echo -e "${Error} Failed to obtain platform IP paramaters " && exit 1
    fi

    GetEnv "KLNKPORT"
    if [[ $? == 0 ]]; then
        KLNKPORT=$ENV
    else
        echo -e "${Error} Failed to obtain Kilolink port parameters " && exit 1
    fi

    GetEnv "KLNKFWDPORT"
    if [[ $? == 0 ]]; then
        KLNKFWDPORT=$ENV
    else
        echo -e "${Error} Failed to obtain Kilolink fowarding port parameters " && exit 1
    fi

    GetEnv "FWDMIN"
    if [[ $? == 0 ]]; then
        FWDMIN=$ENV
    else
        echo -e "${Error} Failed to obtain forwarding minimun parameters " && exit 1
    fi

    GetEnv "FWDMAX"
    if [[ $? == 0 ]]; then
        FWDMAX=$ENV
    else
        echo -e "${Error} Failed to obtain forwarding maximun parameters" && exit 1
    fi

    GetEnv "TUNMIN"
    if [[ $? == 0 ]]; then
        TUNMIN=$ENV
    else
        echo -e "${Error} Failed to obtain TUN minimun parameters " && exit 1
    fi

    GetEnv "TUNMAX"
    if [[ $? == 0 ]]; then
        TUNMAX=$ENV
    else
        echo -e "${Error} Failed to obtain TUN maximun parameters " && exit 1
    fi

    GetEnv "TUNPORT"
    if [[ $? == 0 ]]; then
        TUNPORT=$ENV
    else
        echo -e "${Error} Failed to obtain TUN port parameters " && exit 1
    fi

    GetEnv "TUNUSER"
    if [[ $? == 0 ]]; then
        TUNUSER=$ENV
    else
        echo -e "${Error} Failed to obtain TUN user parameters " && exit 1
    fi

    GetEnv "TUNPASS"
    if [[ $? == 0 ]]; then
        TUNPASS=$ENV
    else
        echo -e "${Error} Failed to obtain TUNPASS parameters" && exit 1
    fi

    GetEnv "TUNREALM"
    if [[ $? == 0 ]]; then
        TUNREALM=$ENV
    else
        echo -e "${Error} Failed to obtain TUNREALM parameters " && exit 1
    fi

    #Delete webpage
    if [[ -d /data/web ]]; then
        rm -rf /data/web
    fi

    #Delete program
    if [[ -d /data/shine ]]; then
        rm -rf /data/shine
    fi

    #Pull up the latest version of the mirror
    echo -e "${Info} Pull up the latest version of kiloview/klnkserver mirror ..."
    docker pull kiloview/klnkserver
    if [[ $? -ne 0 ]]; then
        echo -e "${Error} Failed to pull up the latest version of the mirror" && exit 1
    fi

    echo -e "${Info} Delete the old container..."
    docker rm -f klnkserver

    echo -e "${Info} Rerun the mirror..."
    Run_container
}

# [[ ${release} != "ubuntu" ]] && echo -e "${Error} The script does not support the current system ${release} !" && exit 1
check_status
if [[ $? == 0 ]]; then
    echo -e "${green}Docker is running${plain}"
    echo -e ""
elif [[ $? == 2 ]]; then
    echo -e "${red}The Docker service is not installed, one-click install docker: ${plain}"
    echo -e "${red}curl -fsSL https://get.docker.com | sh${plain}" && exit 1
else
    echo -e "${red}Docker service is installed, but not started.Try to start...${plain}"
    systemctl start docker
    if [[ $? == 0 ]]; then
        echo -e "${green}Success to start Docker server${plain}"
    else
        echo -e "${green}Failed to start Docker server${plain}" && exit 1
    fi
fi

action=$1
if [[ "${action}" == "config" ]]; then
	display_config
elif [[ "${action}" == "log" ]]; then
	log_klnkserver
else
	echo -e "  Kiloview KlnkServer one-click management script ${Red_font_prefix}[v${sh_ver}]${Font_color_suffix}
  ${Green_font_prefix}1.${Font_color_suffix} Install KlnkServer
  ${Green_font_prefix}2.${Font_color_suffix} Update KlnkServer
  ${Green_font_prefix}3.${Font_color_suffix} Uninstall KlnkServer
  "
	menu_status
	echo && read -e -p "Enter the number[1-3]：" num
case "$num" in
	1)
	install_klnkserver
	;;
	2)
	update_klnkserver
	;;
	3)
	uninstall_klnkserver
	;;
	*)
	echo -e "${Error} Enter the correct number [1-3]"
	;;
esac
fi