#!/bin/bash

# LOG_FILE="/home/daystarp/factory_test/factory_test.txt"
# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="${SCRIPT_DIR}/factory_test.txt"

echo "---------------------------" | tee -a "$LOG_FILE"
echo "                            " | tee -a "$LOG_FILE"
echo "Now is $(date +%Y-%m-%d\ %H:%M:%S):" | tee -a "$LOG_FILE"
echo "002: Testing USB port (checking for USB-connected storage)..." | tee -a "$LOG_FILE"

DETECTED=""

# 检查所有 /dev/sdX 设备
for dev in /dev/sd*; do
    [ -b "$dev" ] || continue
    dev_name=$(basename "$dev")

    # 使用 udevadm 检查设备是否来自 USB
    if udevadm info --query=property --name="$dev" | grep -q "ID_BUS=usb"; then
        DETECTED="$dev"
        break
    fi
done

# --------------------------
# 输出结果
# --------------------------
if [ -n "$DETECTED" ]; then
    # 获取大小
    size_blocks=$(cat /sys/block/${DETECTED#/dev/}/size 2>/dev/null)
    size_gb="unknown"
    if [ -n "$size_blocks" ] && [ "$size_blocks" -gt 0 ]; then
        size_gb=$(echo "scale=2; $size_blocks * 512 / 1024 / 1024 / 1024" | bc -l 2>/dev/null || echo "unknown")
    fi

    echo "USB Port OK: USB storage device detected!" | tee -a "$LOG_FILE"
    echo "   Device:     $DETECTED" | tee -a "$LOG_FILE"
    echo "   Size:       ${size_gb} GB" | tee -a "$LOG_FILE"

    # 文件系统（可选）
    fs_type=$(blkid "$DETECTED" -o value -s TYPE 2>/dev/null)
    if [ -n "$fs_type" ]; then
        echo "   Filesystem: $fs_type" | tee -a "$LOG_FILE"
    else
        echo "   Filesystem: Not mounted or unformatted" | tee -a "$LOG_FILE"
    fi

    exit 0
else
    echo "FAILED: No USB storage device detected." | tee -a "$LOG_FILE"
    echo "         Please check USB port or insert a U盘." | tee -a "$LOG_FILE"

    # 调试信息
    echo "Debug: All block devices and their bus:" | tee -a "$LOG_FILE"
    for d in /dev/sd*; do
        [ -b "$d" ] && echo "  $d: $(udevadm info --query=property --name=$d | grep ID_BUS= | cut -d= -f2 || echo unknown)" | tee -a "$LOG_FILE"
    done

    exit 1
fi