#!/bin/sh

progress="$1"

#connect status
echo $progress >/tmp/orayboxvpn_connect_status

log () {

logger -t "【蒲公英组网】" "$1"
}

#log "$progress"

#99: 表示 链接中
# 1: 表示 已组网
# 0: 表示 未组网

# 显示登录页面
#4	-1: 表示 账号错误
#-2: 表示 帐号密码为空
#6	-3: 表示 成员数不足
#5	-4: 表示 登录失败
#2	-5: 表示 服务过期
#1026	-8: 表示 修改密码
#7	-9: 表示 服务被禁
#401 -10: 表示 授权被禁
#-1 -11: 表示 登录故障 这个要区别一下登录失败(登录成功后断开)


# 显示登录成功 未组网页面
#-1 -6: 表示 移除网络
#6	-7: 表示 状态关闭

# err_code=
# vpn_status=
# login_status=

if [ "$progress" == "connected" ] ;then ### 已组网
	vpn_status=1
	log "已组网，尝试连接中..."
elif [ "$progress" == "tryconnect" ] ;then
	log "尝试连接"
elif [ "$progress" == "sn" ] ;then
	vpn_status=99
	login_status=1
	log "vpnid=$2 vpnpwd=$3"
	log "已登录，正在链接中"
elif [ "$progress" == "login_err" ] ;then
	vpn_status=0
	err_code=$2
	if [ "$err_code" == "4" ] ;then
		err_code=-1
		log "帐号错误"
	elif [ "$err_code" == "6" ] ;then
		err_code=-3
		log "成员数不足"
	elif [ "$err_code" == "5" ] ;then
		err_code=-4
		log "登录失败"
	elif [ "$err_code" == "2" ] ;then
		err_code=-5
		log "服务过期"
	elif [ "$err_code" == "7" ] ;then
		err_code=-9
		log "服务被禁"
	elif [ "$err_code" == "401" ] ;then
		err_code=-10
		log "授权被禁"
	elif [ "$err_code" == "403" ] ;then
		err_code=-10
		log "授权被禁"
	elif [ "$err_code" == "-1" ] ;then
		err_code=-11
		log "登录故障，可能登录失败？或登录成功后断开？"
	fi


elif [ "$progress" == "not_in_group" ] ;then ### 未组网
	## not_in_group is not a err
	vpn_status=0
	err_code=0
	login_status=1
	log "已登录，未组网"

elif [ "$progress" == "disconnected" ] ;then
	err_code=$2
	vpn_status=0
	if [ -n "$err_code" ] ;then
		vpn_status=0
		if [ "$err_code" == "-1" ] ;then
			err_code=-6
			log "已断开，移除网络"
		elif [ "$err_code" == "6" ] ;then
			err_code=-7
			log "已断开，状态关闭"
		elif [ "$err_code" == "1026" ] ;then
			err_code=-8
			log "已断开，修改密码"
		fi
		log "已断开 err_code=$err_code"
	fi
fi

if [ -n "$vpn_status" ] ;then
	echo "组网状态：$vpn_status  （99：链接中 1：已组网 0：未组网）"
fi

if [ "$vpn_status" == "1" ]; then
    # 在后台运行 while 循环(下面改成你的对端IP 多个对端就再增加一段代码)
##############################################
    (
    while true; do
        if ping -c 1 -W 2 172.16.0.219 >/dev/null 2>&1; then
            echo "$(date '+%Y-%m-%d %H:%M:%S') 目标 IP: 172.16.0.219 已连通，退出循环。" >> "$LOG_FILE"
            logger -t "【蒲公英组网】" "已ping通目标 IP: 172.16.0.219 "
            break  # 退出 while 循环
        fi
        echo "$(date '+%Y-%m-%d %H:%M:%S') 目标 IP: 172.16.0.219 未连通，继续尝试..." > /tmp/var/ping.log
        sleep 1
    done
    ) &
#################################################
fi

