#!/bin/bash

# 获取 enP8p1s0 的 IPv4 地址

INTERFACE="enP8p1s0"
# 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 "001: Begin to test connector" | tee -a "$LOG_FILE"

# 检查接口是否存在
if ! ip link show "$INTERFACE" > /dev/null 2>&1; then
    echo "Error: Interface $INTERFACE not found" | tee -a "$LOG_FILE"
    exit 1
fi

# 获取 IPv4 地址
IP=$(ip -4 addr show "$INTERFACE" | grep inet | awk '{print $2}' | cut -d'/' -f1)

if [ -z "$IP" ]; then
    echo "Error: No IPv4 address assigned to $INTERFACE" | tee -a "$LOG_FILE"
    exit 1
else
    echo "$INTERFACE has IP: $IP" | tee -a "$LOG_FILE"
fi

# 可选：用这个 IP 去 ping 目标（比如 192.168.144.103）
PING_TARGET="192.168.144.103"
if ping -I "$IP" -c 2 -W 3 "$PING_TARGET" > /dev/null 2>&1; then
    echo "SUCCESS: $IP can reach $PING_TARGET" | tee -a "$LOG_FILE"
else
    echo "FAILED: $IP cannot reach $PING_TARGET" | tee -a "$LOG_FILE"
    exit 2
fi

echo "All checks passed for $INTERFACE with IP $IP." | tee -a "$LOG_FILE"
exit 0