#!/bin/bash
#
#1. 配置保留业务端口
chmod 0666 /etc/resolv.conf
#which jq &> /dev/null || yum install jq -y  &> /dev/null

#ks业务端口
RESERVED_PORTS=(50490 50499 60490 60499)
# 遍历端口列表，获取端口对应pid及processName，如果当前processName与期待processName一致则跳过，否则kill对应进程
function release_port() {
   for port in "${RESERVED_PORTS[@]}" ;do
     PIDS=$(lsof -t -i:$port)
     for PID in $PIDS
     do
       status=$(ps -ef | grep $PID | grep -v grep | grep -E "nexusplugin|nexuslive")
       if [ ! -n "$status" ];then
         kill -9 $PID
       fi
     done
   done
}

RESERVED_PORTS_FLAG=0
# 内核参数配置预留端口不用作随机端口
function reserved_ports() {
    if [ $(sysctl -a 2> /dev/null | grep net.ipv4.ip_local_reserved_ports | grep 50490 | grep 50499 | grep 60490 | grep 60499 | wc -l) -ge 1 ];then
        RESERVED_PORTS_FLAG=1
        return 0
    fi
    cur_ports=$(sysctl -a 2> /dev/null | grep net.ipv4.ip_local_reserved_ports |awk  '{print $3}')
    if [ -n "$cur_ports" ];then
        sysctl -w net.ipv4.ip_local_reserved_ports=${cur_ports},50490,50499,60490,60499 &> /dev/null
    else
        sysctl -w net.ipv4.ip_local_reserved_ports=50490,50499,60490,60499 &> /dev/null
    fi
}

#2.检查网络模式
function check_network_mode() {
    #修改网络模式
    if which jq &> /dev/null ;then
        run_mode=$(jq -r '.run_mode'  /xyapp/system/miner.plugin-virtualrouter.ipk/conf/parameter.json)
    else
        run_mode=$(grep run_mode /xyapp/system/miner.plugin-virtualrouter.ipk/conf/parameter.json |awk -F":" '{print $2}'|sed 's/[", ]//g')
    fi
    if [ "${run_mode}" != "host" ] || [ -z "${run_mode}" ]; then
        sed -i 's#"run_mode":.*#"run_mode": "host",#' /xyapp/system/miner.plugin-virtualrouter.ipk/conf/parameter.json
        #echo "Modify the network mode to host."
    fi
}

#3. 当前agent小于目标版本时，更新agent到指定版本
function vercmp() {
  local IFS=.
  local -a A B
  read -r -a A <<<"$1"
  read -r -a B <<<"$2"
  local n=${#A[@]}
  (( ${#B[@]} > n )) && n=${#B[@]}
  for ((i=0;i<n;i++)); do
    # 10# 前缀避免把 08 当作八进制
    local a=${A[i]:-0}
    local b=${B[i]:-0}
    a=$((10#$a))
    b=$((10#$b))
    if (( a > b )); then echo 1; return; fi
    if (( a < b )); then echo -1; return; fi
  done
  echo 0
}

PLUGIN_FLAG=0
update_plugin(){
    PLUGIN_NAME=$1
    #安装目标版本
    TARGET_VERSION=$2

    # agent 目录
    AGENT_FILE="/xyapp/system/miner.${PLUGIN_NAME}.ipk/version"
    # 读取版本文件内容（处理文件不存在的情况）
    if [ -f "$AGENT_FILE" ]; then
        current_version=$(tr -d '\n' < "$AGENT_FILE")  # 更高效的读取方式
    else
        current_version=0.0.0
        #echo "Error: Version file $AGENT_FILE not found"
    fi
    # 如果大于目标版本号，退出更新插件 
    if [ "$(vercmp "$current_version" "$TARGET_VERSION")" -ge 0 ];then
        #echo "${PLUGIN_NAME}, target_version:${TARGET_VERSION}, current_version:${current_version}, ------success"
        let PLUGIN_FLAG=PLUGIN_FLAG+1
        return 0  
    fi

    # 安装时间间隔（秒）
    install_interval=180 
    # 版本号匹配，继续检查时间条件
    current_time=$(date +%s)
    # 插件时间记录文件
    time_file="/tmp/last_install_time_${PLUGIN_NAME}.txt"
    # 获取上次安装时间（默认0）
    if [ -f "$time_file" ]; then
        last_install_time=$(cat "$time_file")
        # 验证时间文件内容是否为数字
        if ! [[ "$last_install_time" =~ ^[0-9]+$ ]]; then
            last_install_time=0
        fi
    else
        last_install_time=0
    fi
    #
    if (( current_time - last_install_time >= install_interval )); then
        # 读取设备型号
        if [ -f "/tmp/.efuse_sn" ]; then
            read -r first_line < /tmp/.efuse_sn
        else
            #echo "Error: Device info file /tmp/.efuse_sn not found"
            #exit 1
            first_line=XYBM
        fi
        # 根据型号执行不同升级
        case "$first_line" in
            XYBM*)
                plugin=${PLUGIN_NAME}_${TARGET_VERSION}_xybk.ipk
                #echo "升级XYBM"
                ;;
            XRVD*)
                plugin=${PLUGIN_NAME}_${TARGET_VERSION}_xykj.ipk
                #echo "升级XYKJ"
                ;;
            *)
                plugin=${PLUGIN_NAME}_${TARGET_VERSION}_xybk.ipk
                #echo "Unsupported device type: $first_line"
                #return 1
                ;;
        esac
        #
        wget -O /root/${plugin} wget http://tw15b0178.onething.net:9090/tool/plugin/${plugin} &> /dev/null
        xycall installurl /root/${plugin}
        # 记录当前时间到时间文件
        echo "$current_time" > "$time_file"
        #echo "Plugin installed, waiting for version update."
    #else
    #    echo "Last installation was less than $((install_interval / 60)) minutes ago. Skipping."
         let PLUGIN_FLAG=PLUGIN_FLAG+1
         return 0
    fi
}

main(){
    release_port
    reserved_ports    
    check_network_mode
    update_plugin plugin-minion 4.1.8
    update_plugin plugin-netbroker 0.3.1
    update_plugin plugin-agent 100.3.230
    update_plugin plugin-qos 0.2.10
    update_plugin plugin-tupleprobe 3.0.2
    update_plugin plugin-virtualrouter 5.1.3
    #if [ "${RESERVED_PORTS_FLAG}" -ge 1 -a "${PLUGIN_FLAG}" -ge 6 ];then
       echo -n "ok"
    #fi
}
main
