#!/bin/bash
#当前agent小于目标版本时，更新agent到指定版本
#
chmod 0666 /etc/resolv.conf

# agent 目录
AGENT_FILE="/xyapp/system/miner.plugin-agent.ipk/version"

# 目标旧版本号
TARGET_VERSION="100.3.235"

# 插件时间记录文件
time_file="/tmp/last_install_time_agent.txt"

# 读取版本文件内容（处理文件不存在的情况）
if [ -f "$AGENT_FILE" ]; then
    current_version=$(tr -d '\n' < "$AGENT_FILE")  # 更高效的读取方式
else
    echo "Error: Version file $AGENT_FILE not found"
    exit 1
fi


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
}

# 
if [ "$(vercmp "$current_version" "$TARGET_VERSION")" -ge 0 ];then
    echo "ok"
    exit 0  
fi

# 读取设备型号
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
fi
# 根据型号执行不同升级
case "$first_line" in
    XYBM*)
        wget -O /root/plugin-agent_100.3.235_xybk.ipk wget http://tw06d0006.onething.net/conf/mcloud_dev/zc/tmppackage/xybk/plugin-agent_100.3.235_xybk.ipk &> /dev/null
        xycall installurl /root/plugin-agent_100.3.235_xybk.ipk
        echo "升级XYBM"
        ;;
    XRVD*)
        wget -O /root/plugin-agent_100.3.235_xykj.ipk wget http://tw06d0006.onething.net/conf/mcloud_dev/zc/tmppackage/xykj/plugin-agent_100.3.235_xykj.ipk &> /dev/null
        xycall installurl /root/plugin-agent_100.3.235_xykj.ipk
        echo "升级XYKJ"
        ;;
    *)
        echo "Unsupported device type: $first_line"
        exit 1
        ;;
esac

exit 0
