#!/bin/sh /etc/rc.common
# Copyright (C) 2008-2020 OpenWrt.org

START=99
USE_PROCD=1
size="$(df -k | awk '/\/overlay$/ {sub(/K$/, "", $4); print $4}')"

check () {
if [ ! -z "$checkip" ] ; then
  echo ' ' >/tmp/easytier_check
  cat > /tmp/easytier_check<<'EOF'
#!/bin/sh
time="$(($(uci -q get easytier.@easytier[0].checktime) * 60))"
  if [ -z "$time" ] ;then
     time=120
     uci -q set easytier.@easytier[0].checktime=2
     uci commit easytier
  fi 
while true; do
  if [ "$(uci -q get easytier.@easytier[0].enabled)" = "1" ] ; then
    ping -c 3 223.5.5.5 -w 5 >/dev/null 2>&1
    if [ "$?" == "0" ]; then
        if [ ! -z "$(uci -q get easytier.@easytier[0].checkip)" ] ; then
           online=""
           for ip in $(uci -q get easytier.@easytier[0].checkip); do
           ms=`echo $(ping -4 $ip  -c 2 -w 4 -q) | awk -F '/' '{print $4}'`
           [ ! -z "$ms" ] && echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 通断检测：${ip} 延迟：${ms}ms " >>/tmp/easytier.log && online=1
           [ -z "$ms" ] && echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 通断检测：${ip} 网络中断 " >>/tmp/easytier.log
           done     
           [ "$online" != "1" ] && echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 通断检测：$(uci -q get easytier.@easytier[0].checkip) 所有指定IP皆无法ping通,重新启动程序！ " >>/tmp/easytier.log && /etc/init.d/easytier restart
        fi
     else
        echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 通断检测：检测到互联网未能成功访问，跳过检测 " >>/tmp/easytier.log
    fi
 else
 echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 通断检测：程序已关闭，退出检测 " >>/tmp/easytier.log
 /etc/init.d/easytier restart
 break
 fi
sleep $((time))
[ "$(du -k /log/easytier.log | cut -f1)" = "1000" ] && echo " " >/tmp/easytier.log
done
EOF
  chmod +x /tmp/easytier_check
  /tmp/easytier_check &
fi
}

start_et() {
                local cfg="$1"
		local enabled easytierbin
		config_get_bool enabled "$cfg" 'enabled' '0'
		[ "$enabled" = "1" ] || return 1
                config_get easytierbin "$cfg" 'easytierbin' '/tmp/easytier-core'
                echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : easytier-core_${cpucore}开始启动" >>/tmp/easytier.log
                #test -z "`opkg list-installed|grep kmod-tun`" && echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 缺少kmod-tun插件" >>/tmp/easytier.log
                path=$(dirname "$easytierbin")
                if [ -f /tmp/easytier-core ] || [ -f /tmp/easytier-cli ] && [ "${path:0:4}" != "/tmp" ] ;then
                   chmod +x /tmp/easytier-core 2>/dev/null
                   chmod +x /tmp/easytier-cli 2>/dev/null
                   echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 找到上传的程序/tmp/easytier-core，替换为$easytierbin " >>/tmp/easytier.log
                   upsize="$(du -k /tmp/easytier-core | cut -f1)"
                   result=$(expr $size - $upsize)
                   if [ $(($(/tmp/easytier-core -h | wc -l))) -gt 3 ] && [ "$result" -gt 2000 ] ; then
                     mv -f /tmp/easytier-core "$easytierbin" 2>/dev/null
                     mv -f /tmp/easytier-cli "${path}/easytier-cli" 2>/dev/null
                     else
                     echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 无法替换，上传的程序不完整或自定义路径的可用空间不足，当前空间剩余${size}kb" >>/tmp/easytier.log
                   fi
                fi
                if [ ! -f "$easytierbin" ] && [ "$size" -lt 4000 ] ; then
                    echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 自定义程序路径的可用空间不足，当前可用空间剩余${size}kb,自动切换为内存/tmp/easytier-core" >>/tmp/easytier.log
                    sed -i "/easytierbin/c option easytierbin '/tmp/easytier-core' " /etc/config/easytier 
                    easytierbin=/tmp/easytier-core
                fi
		if [ $(($($easytierbin -h | wc -l))) -lt 3 ] || [ ! -f "$easytierbin" ] ; then
		 newtag="$( curl --connect-timeout 3 --user-agent 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'  https://api.github.com/repos/EasyTier/EasyTier/releases/latest  2>&1 | grep 'tag_name' | cut -d\" -f4 )"
		 [ -z "$newtag"] && newtag=v1.1.0
		 echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 未找到程序 $easytierbin 开始在线下载${newtag}，下载较慢耐心等候" >>/tmp/easytier.log
                 mkdir -p "$path"
	         curl -L -k -s -o /tmp/easytier.zip --connect-timeout 10 --retry 3 "http://gh.ddlc.top/https://github.com/EasyTier/EasyTier/releases/download/${newtag}/easytier-${core_url}-${newtag}.zip" || curl -L -k -s -o /tmp/easytier.zip --connect-timeout 10 --retry 3 "https://hub.gitmirror.com/https://github.com/EasyTier/EasyTier/releases/download/${newtag}/easytier-${core_url}-${newtag}.zip" || curl -L -k -s -o /tmp/easytier.zip --connect-timeout 10 --retry 3 "https://github.com/EasyTier/EasyTier/releases/download/${newtag}/easytier-${core_url}-${newtag}.zip"
	         unzip -q -o /tmp/easytier.zip -d $path 
                 chmod +x "$easytierbin"
 if [ $(($($easytierbin -h | wc -l))) -gt 3 ]; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : ${easytierbin} 下载成功" >>/tmp/easytier.log
 else
   uci -q set easytier.@easytier[0].enabled=0
   uci commit easytier
   echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : $easytierbin 下载失败，请手动下载上传程序,程序退出" >>/tmp/easytier.log
   return 1
 fi
                fi
                chmod +x "$easytierbin"
                ver="$($easytierbin -h | grep version | awk -F ':' {'print $2'})"
                [ ! -z "$ver" ] && echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : ${easytierbin}当前版本号-${ver} " >>/tmp/easytier.log
                killall easytier_check >/dev/null 2>&1
                killall easytier-core >/dev/null 2>&1
                killall -9 easytier-core >/dev/null 2>&1
		local network_name network_secret mode ipaddr peeradd external_node rpc_portal listenermode
		local listeners desvice_name instance_name vpn_portal mtu default_protocol disable_encryption
		local multi_thread disable_ipv6 latency_first exit_node exit_nodes log check checkip proxy_network
		config_get network_name "$cfg" 'network_name'
                config_get network_secret "$cfg" 'network_secret'
                config_get mode "$cfg" 'mode'
                config_get ipaddr "$cfg" 'ipaddr'
                config_get external_node "$cfg" 'external_node'
                config_get proxy_network "$cfg" 'proxy_network'
                config_get rpc_portal "$cfg" 'rpc_portal'
                config_get listenermode "$cfg" 'listenermode'
                config_get listeners "$cfg" 'listeners'
                config_get desvice_name "$cfg" 'desvice_name'
                config_get instance_name "$cfg" 'instance_name'
                config_get vpn_portal "$cfg" 'vpn_portal'
		 config_get mtu "$cfg" 'mtu' '1400'
                config_get default_protocol "$cfg" 'default_protocol'
                config_get_bool disable_encryption "$cfg" 'disable_encryption' '0'
                config_get_bool multi_thread "$cfg" 'multi_thread' '0'
                config_get_bool disable_ipv6 "$cfg" 'disable_ipv6' '0'
                config_get_bool latency_first "$cfg" 'latency_first' '0'
                config_get_bool exit_node "$cfg" 'exit_node' '0'
                config_get exit_nodes "$cfg" 'exit_nodes'
                config_get_bool log "$cfg" 'log' '0'
                config_get_bool check "$cfg" 'check' '0'
                config_get checkip "$cfg" 'checkip'
                
		procd_open_instance "easytier"
		procd_set_param command "$easytierbin"
		[ -z "$network_name" ] || procd_append_param command --network-name "$network_name"
		[ -z "$network_secret" ] || procd_append_param command --network-secret "$network_secret"
		[ "$mode" = "静态指定" ] && [ ! -z "$ipaddr" ] && procd_append_param command -i "$ipaddr"
		[ "$mode" = "自动分配" ] && procd_append_param command -d
		if [ ! -z "$peeradd" ] ; then
                  if [[ "$(grep "list peeradd" /etc/config/easytier | awk '{print $3}' | wc -l ) " -eq 1 ]]; then
                    procd_append_param command -p "$peeradd"
                  else
                    for peeraddr in $(cat /etc/config/easytier | grep 'list peeradd'  | awk -F 'list peeradd' '{print $2}' | sed "s/'/\n/g" | tr -d " ' "); do
                    procd_append_param command -p "$peeraddr"
                   done
                   fi
                fi
                if [ ! -z "$proxy_network" ] ; then
                  if [[ "$(grep "list proxy_network" /etc/config/easytier | awk '{print $3}' | wc -l ) " -eq 1 ]]; then
                    procd_append_param command -n "$proxy_network"
                  else
                    for proxy_networks in $(cat /etc/config/easytier | grep 'list proxy_network'  | awk -F 'list proxy_network' '{print $2}' | sed "s/'/\n/g" | tr -d " ' "); do
                    procd_append_param command -n "$proxy_networks"
                   done
                   fi
                fi
		[ -z "$external_node" ] || procd_append_param command -e "$external_node"
		[ -z "$rpc_portal" ] || procd_append_param command -r "$rpc_portal"
		[ "$listenermode" = "ON" ] && [ ! -z "$listeners" ] && procd_append_param command -l "$listeners"
		[ "$listenermode" = "OFF" ] && procd_append_param command --no-listener
		[ -z "$desvice_name" ] || procd_append_param command --hostname "$desvice_name"
		[ -z "$instance_name" ] || procd_append_param command -m "$instance_name"
		[ -z "$vpn_portal" ] || procd_append_param command --vpn-portal "$vpn_portal"
		[ -z "$mtu" ] || procd_append_param command --mtu "$mtu"
		[ -z "$default_protocol" ] || procd_append_param command --default-protocol "$default_protocol"
		[ "$disable_encryption" = "0" ] || procd_append_param command -u
		[ "$multi_thread" = "0" ] || procd_append_param command --multi-thread
		[ "$disable_ipv6" = "0" ] || procd_append_param command --disable-ipv6
		[ "$latency_first" = "0" ] || procd_append_param command --latency-first
		[ "$exit_node" = "0" ] || procd_append_param command --enable-exit-node
		[ -z "$exit_nodes" ] || procd_append_param command --exit-nodes "$exit_nodes"
		[ "$log" = "1" ] && procd_append_param command --file-log-level "info" 
		[ "$log" = "1" ] && procd_append_param command --file-log-dir "/tmp"
		[ "$log" = "0" ] && procd_append_param command --file-log-level "off"
		[ ! -z "$instance_name" ] && ln -sf /tmp/easytier-${instance_name}.${date_time} /tmp/easytier.log
		
		procd_set_param limits core="unlimited"
		procd_set_param limits nofile="1000000 1000000"
		procd_set_param stdout 1
		procd_set_param stderr 1
		procd_set_param respawn
		procd_close_instance

                
                if [ ! -z "$listeners" ] ; then
                    tcpudp_port="$listeners"
                    wgws_port=$((tcpudp_port + 1))
                    wss_port=$((tcpudp_port + 2))
                    
	            uci -q delete firewall.easytier_tcp_udp
		    uci set firewall.easytier_tcp_udp=rule
		    uci set firewall.easytier_tcp_udp.name="easytier_tcp_udp"
		    uci set firewall.easytier_tcp_udp.target="ACCEPT"
		    uci set firewall.easytier_tcp_udp.src="wan"
		    uci set firewall.easytier_tcp_udp.proto="all"
		    uci set firewall.easytier_tcp_udp.dest_port="$tcpudp_port"
		    uci set firewall.easytier_tcp_udp.enabled="1"
		    
		    uci -q delete firewall.easytier_wss
		    uci set firewall.easytier_wss=rule
		    uci set firewall.easytier_wss.name="easytier_wss"
		    uci set firewall.easytier_wss.target="ACCEPT"
		    uci set firewall.easytier_wss.src="wan"
		    uci set firewall.easytier_wss.proto="all"
		    uci set firewall.easytier_wss.dest_port="$wss_port"
		    uci set firewall.easytier_wss.enabled="1"
		    
		    uci -q delete firewall.easytier_wg_ws
		    uci set firewall.easytier_wg_ws=rule
		    uci set firewall.easytier_wg_ws.name="easytier_wg_ws"
		    uci set firewall.easytier_wg_ws.target="ACCEPT"
		    uci set firewall.easytier_wg_ws.src="wan"
		    uci set firewall.easytier_wg_ws.proto="all"
		    uci set firewall.easytier_wg_ws.dest_port="$wgws_port"
		    uci set firewall.easytier_wg_ws.enabled="1"
	        fi
		
	        if [ -z "$(uci -q get network.EasyTier)" ];  then				
			uci set network.EasyTier='interface'
                       uci set network.EasyTier.device=tun0
                       uci set network.EasyTier.ifname=tun0
		fi
		if [ -z "$(uci -q get firewall.easytierzone)" ];  then
				uci set firewall.easytierzone='zone'
				uci set firewall.easytierzone.input='ACCEPT'
				uci set firewall.easytierzone.output='ACCEPT'
				uci set firewall.easytierzone.forward='ACCEPT'
				uci set firewall.easytierzone.masq='1'
                                uci set firewall.easytierzone.mtu_fix='1'
				uci set firewall.easytierzone.name='EasyTier'
				uci set firewall.easytierzone.network='EasyTier'
		fi
		uci set firewall.easytierfwlan=forwarding
		uci set firewall.easytierfwlan.dest='lan'
		uci set firewall.easytierfwlan.src='EasyTier'
                uci set firewall.easytierfwwan=forwarding
		uci set firewall.easytierfwwan.dest='wan'
		uci set firewall.easytierfwwan.src='EasyTier'
                uci set firewall.lanfweasytier=forwarding
		uci set firewall.lanfweasytier.dest='EasyTier'
		uci set firewall.lanfweasytier.src='lan'
                uci set firewall.wanfweasytier=forwarding
		uci set firewall.wanfweasytier.dest='EasyTier'
		uci set firewall.wanfweasytier.src='wan'
                [ -n "$(uci changes network)" ] && uci commit network && /etc/init.d/network reload >/dev/null 2>&1
		[ -n "$(uci changes firewall)" ] && uci commit firewall && /etc/init.d/firewall reload >/dev/null 2>&1
		#sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1
                [ ! -z "$checkip" ] && check
                echo `date +%s` > /tmp/easytier_time



}

start_service() {
	config_load 'easytier'
	date_time=$(TZ='Asia/Shanghai' date +'%Y-%m-%d')
	ins_name=$(uci -q set easytier.@easytier[0].instance_name)
	
	if [ ! -z "$ins_name" ] ; then
	  touch /tmp/easytier-${ins_name}.${date_time}
	  ln -sf /tmp/easytier-${ins_name}.${date_time} /tmp/easytier.log
	else
	  touch /tmp/easytier-default.${date_time}
          ln -sf /tmp/easytier-default.${date_time} /tmp/easytier.log
        fi
	cputype=$(uname -ms | tr ' ' '_' | tr '[A-Z]' '[a-z]')
        [ -n "$(echo $cputype | grep -E "linux.*armv.*")" ] && cpucore="arm" ; core_url="arm-unknown-linux-musleabi"
        [ -n "$(echo $cputype | grep -E "linux.*armv7.*")" ] && [ -n "$(cat /proc/cpuinfo | grep vfp)" ] && [ ! -d /jffs/clash ] && cpucore="armv7" ; core_url="armv7-unknown-linux-musleabi"
        [ -n "$(echo $cputype | grep -E "linux.*aarch64.*|linux.*armv8.*")" ] && cpucore="aarch64" ; core_url="aarch64-unknown-linux-musl"
        [ -n "$(echo $cputype | grep -E "linux.*86.*")" ] && cpucore="i386" ; core_url=""
        [ -n "$(echo $cputype | grep -E "linux.*86_64.*")" ] && cpucore="x86_64" ; core_url="x86_64-unknown-linux-musl"
        if [ -n "$(echo $cputype | grep -E "linux.*mips.*")" ] ; then
           mipstype=$(echo -n I | hexdump -o 2>/dev/null | awk '{ print substr($2,6,1); exit}') 
           [ "$mipstype" = "0" ] && cpucore="mips" ; core_url="mips-unknown-linux-musl" || cpucore="mipsle" ; core_url="mipsel-unknown-linux-musl"
        fi
        
        #test -z "`opkg list-installed|grep curl`" && echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 缺少curl插件" >>/tmp/easytier.log
        #test -z "`opkg list-installed|grep luci-lib-fs`" && echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 缺少luci-lib-fs插件" >>/tmp/easytier.log
        #test -z "`opkg list-installed|grep unzip`" && echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 缺少unzip插件" >>/tmp/easytier.log
	config_foreach start_et 'easytier'
}

stop_service() {
                killall easytier_check >/dev/null 2>&1
                killall easytier-core >/dev/null 2>&1
                killall -9 easytier-core >/dev/null 2>&1
                uci -q delete network.EasyTier >/dev/null 2>&1
                uci -q delete firewall.easytierzone >/dev/null 2>&1
	        uci -q delete firewall.easytierfwlan >/dev/null 2>&1
	        uci -q delete firewall.easytierfwwan >/dev/null 2>&1
	        uci -q delete firewall.lanfweasytier >/dev/null 2>&1
	        uci -q delete firewall.wanfweasytier >/dev/null 2>&1
                uci -q delete firewall.easytier_tcp_udp >/dev/null 2>&1
                uci -q delete firewall.easytier_wg_ws >/dev/null 2>&1
                uci -q delete firewall.easytier_wg_wss >/dev/null 2>&1
                [ -n "$(uci changes network)" ] && uci commit network && /etc/init.d/network reload >/dev/null 2>&1
	        [ -n "$(uci changes firewall)" ] && uci commit firewall && /etc/init.d/firewall reload >/dev/null 2>&1 
                rm -rf /tmp/easytier-cli_peer /tmp/easytier-cli_connector /tmp/easytier-cli_stun /tmp/easytier-cli_route >/dev/null 2>&1
                rm -rf /tmp/easytier-cli_peer-center /tmp/easytier-cli_vpn-portal /tmp/easytier_cmd >/dev/null 2>&1
                rm -rf /tmp/easytier-*.* /tmp/easytier.log >/dev/null 2>&1
                rm -rf /tmp/easytiernew.tag /tmp/easytier.tag >/dev/null 2>&1
                echo "$(date '+%Y-%m-%d %H:%M:%S') easytier : 停止运行" >>/tmp/easytier.log
}

reload_service() {
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger "eaytier"
        procd_add_interface_trigger "interface.*.up" wan /etc/init.d/easytier reload
}
