#!/bin/bash

# 锁文件，防止并发执行
LOCK_FILE="/var/lock/upgrade_rtl8188_driver.lock"
exec 200>"$LOCK_FILE"
flock -n 200 || { echo "Another instance is running, exiting."; exit 0; }

# Penalty mechanism for consecutive download failures
FAILURE_COUNT_FILE="/tmp/.download_failure_count"
PENALTY_LOCK_FILE="/tmp/.download_penalty_until"

get_uptime() {
    local up
    if read -r up _ < /proc/uptime 2>/dev/null; then
        echo ${up%.*}
    else
        echo 0
    fi
}

check_penalty_wait() {
    if [[ -f "$PENALTY_LOCK_FILE" ]]; then
        local penalty_until=$(cat "$PENALTY_LOCK_FILE" 2>/dev/null)
        local current_uptime=$(get_uptime)
        if [[ -n "$penalty_until" ]] && [[ $current_uptime -lt $penalty_until ]]; then
            local wait_time=$((penalty_until - current_uptime))
            echo "Download penalty active, waiting ${wait_time}s"
            sleep $wait_time
        fi
        rm -f "$PENALTY_LOCK_FILE"
    fi
}

record_download_failure() {
    local count=0
    [[ -f "$FAILURE_COUNT_FILE" ]] && count=$(cat "$FAILURE_COUNT_FILE" 2>/dev/null)
    count=$((count + 1))
    echo $count > "$FAILURE_COUNT_FILE"
    
    if [[ $count -ge 3 ]]; then
        # Random 10-30 minutes (600-1800 seconds)
        local penalty_seconds=$((600 + RANDOM % 1201))
        local penalty_until=$(($(get_uptime) + penalty_seconds))
        echo $penalty_until > "$PENALTY_LOCK_FILE"
        echo "3 consecutive download failures, penalty ${penalty_seconds}s applied"
        echo 0 > "$FAILURE_COUNT_FILE"
    fi
}

record_download_success() {
    echo 0 > "$FAILURE_COUNT_FILE"
}

sha256="b74738acf06be1fd1d2a20b1db801914f50345c466c5f4a1bf507ea1ef6fc41f"
upgrade_flag="/usr/local/dragino/flag/.upgrade_flag_250820"
server_address="http://repo.dragino.com/release/driver/lps8v2/rtl8188"
driver_name="roma_40_20_mbo_pwrlim_exc.ko"
kernel_dir="/lib/modules/$(uname -r)/kernel/drivers/net/wireless/realtek"
tmp_file="/tmp/$driver_name"

# 如果已经升级过就退出
[[ -f "$upgrade_flag" ]] && rm /etc/cron.d/update_rtl8188_driver_250820 && exit 0

# 检查惩罚等待
check_penalty_wait

# 下载文件
random_number=$(($RANDOM%60))
sleep $random_number
if wget -q --show-progress --timeout=30 --tries=3 -P /tmp "$server_address/$driver_name"; then
    record_download_success
else
    record_download_failure
    exit 1
fi

# 校验文件存在
[[ -f "$tmp_file" ]] || exit 1

# 校验哈希
file_hash=$(sha256sum "$tmp_file" | awk '{print $1}')
if [[ "$file_hash" != "$sha256" ]]; then
    echo "Hash mismatch! expected=$sha256 got=$file_hash"
    rm -f "$tmp_file"
    exit 1
fi

# 替换驱动
mv "$tmp_file" "$kernel_dir/rtl8188fu.ko" || exit 1

# 生成升级标志
touch "$upgrade_flag"
echo "Driver upgraded successfully."
