#!/bin/bash
# ============================================================
# GUARDiA SM | ping_test.sh
# 대상: 네트워크 연결 테스트 (ICMP ping + TCP port check)
# 파라미터: TARGETS="host1:80 host2:443 host3:8080"
#            (형식: hostname_or_ip[:port])
#           PING_COUNT=5 PING_TIMEOUT=2
#           PACKET_LOSS_WARN=10 LATENCY_WARN=100
#           TCP_TIMEOUT=5
# ============================================================
set -euo pipefail
TARGETS=${TARGETS:-"localhost:80"}
PING_COUNT=${PING_COUNT:-5}
PING_TIMEOUT=${PING_TIMEOUT:-2}
PACKET_LOSS_WARN=${PACKET_LOSS_WARN:-10}
LATENCY_WARN=${LATENCY_WARN:-100}
TCP_TIMEOUT=${TCP_TIMEOUT:-5}
OK="[OK]"; WARN="[WARN]"; CRIT="[CRIT]"
SEP="─────────────────────────────────────────"
RESULT=0

echo "======================================================"
echo " GUARDiA SM 점검 | 네트워크 연결 테스트 | $(hostname -s)"
echo " 점검 시각: $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "======================================================"

# ── 1. ICMP Ping 테스트 ───────────────────────────────────
echo; echo "[$SEP] 1. ICMP Ping 테스트"
printf " %-30s %-10s %-12s %-12s %s\n" "호스트" "손실률" "평균지연(ms)" "최대지연(ms)" "상태"
echo " $(printf '%.0s─' {1..70})"

for TARGET in $TARGETS; do
    HOST=$(echo "$TARGET" | cut -d: -f1)
    PING_OUT=$(ping -c "$PING_COUNT" -W "$PING_TIMEOUT" "$HOST" 2>/dev/null || echo "FAILED")
    if echo "$PING_OUT" | grep -q "FAILED\|unreachable\|unknown host"; then
        printf " %-30s %-10s %-12s %-12s %s\n" "$HOST" "100%" "N/A" "N/A" "${CRIT}"
        RESULT=2
    else
        LOSS=$(echo "$PING_OUT" | grep "packet loss" | \
            grep -oP '\d+(?=% packet loss)' | head -1 || echo 100)
        AVG=$(echo "$PING_OUT" | grep "rtt min\|round-trip" | \
            grep -oP '[\d.]+/[\d.]+/[\d.]+' | cut -d/ -f2 || echo "N/A")
        MAX=$(echo "$PING_OUT" | grep "rtt min\|round-trip" | \
            grep -oP '[\d.]+/[\d.]+/[\d.]+' | cut -d/ -f3 || echo "N/A")

        if [ "${LOSS:-100}" -ge 50 ]; then
            printf " %-30s %-10s %-12s %-12s %s\n" "$HOST" "${LOSS}%" "${AVG}ms" "${MAX}ms" "${CRIT}"
            RESULT=2
        elif [ "${LOSS:-100}" -ge "$PACKET_LOSS_WARN" ]; then
            printf " %-30s %-10s %-12s %-12s %s\n" "$HOST" "${LOSS}%" "${AVG}ms" "${MAX}ms" "${WARN}"
            [ $RESULT -lt 1 ] && RESULT=1
        else
            # 지연 체크
            if echo "$AVG" | grep -qE "^[0-9]" && \
               awk "BEGIN{exit !(\"${AVG:-0}\"+0 > $LATENCY_WARN)}" 2>/dev/null; then
                printf " %-30s %-10s %-12s %-12s %s\n" "$HOST" "${LOSS}%" "${AVG}ms" "${MAX}ms" "${WARN} 지연"
                [ $RESULT -lt 1 ] && RESULT=1
            else
                printf " %-30s %-10s %-12s %-12s %s\n" "$HOST" "${LOSS}%" "${AVG}ms" "${MAX}ms" "${OK}"
            fi
        fi
    fi
done

# ── 2. TCP 포트 연결 테스트 ───────────────────────────────
echo; echo "[$SEP] 2. TCP 포트 연결 테스트"
printf " %-30s %-10s %-15s %s\n" "호스트" "포트" "응답시간(ms)" "상태"
echo " $(printf '%.0s─' {1..65})"

for TARGET in $TARGETS; do
    HOST=$(echo "$TARGET" | cut -d: -f1)
    PORT=$(echo "$TARGET" | cut -s -d: -f2)
    [ -z "$PORT" ] && continue

    START=$(date +%s%N 2>/dev/null || echo 0)
    if command -v nc &>/dev/null; then
        NC_RESULT=$(nc -z -w "$TCP_TIMEOUT" "$HOST" "$PORT" 2>/dev/null && echo "OK" || echo "FAIL")
    elif command -v bash &>/dev/null; then
        NC_RESULT=$(timeout "$TCP_TIMEOUT" bash -c \
            "echo >/dev/tcp/${HOST}/${PORT}" 2>/dev/null && echo "OK" || echo "FAIL")
    else
        NC_RESULT="SKIP"
    fi
    END=$(date +%s%N 2>/dev/null || echo 0)
    ELAPSED=$(( (END - START) / 1000000 ))

    if [ "$NC_RESULT" = "OK" ]; then
        printf " %-30s %-10s %-15s %s\n" "$HOST" "$PORT" "${ELAPSED}ms" "${OK}"
    elif [ "$NC_RESULT" = "SKIP" ]; then
        printf " %-30s %-10s %-15s %s\n" "$HOST" "$PORT" "N/A" "${WARN} (nc/bash 없음)"
    else
        printf " %-30s %-10s %-15s %s\n" "$HOST" "$PORT" "${ELAPSED}ms" "${CRIT}"
        RESULT=2
    fi
done

# ── 3. DNS 해석 테스트 ────────────────────────────────────
echo; echo "[$SEP] 3. DNS 해석 테스트"
DNS_SERVERS=$(cat /etc/resolv.conf 2>/dev/null | grep "^nameserver" | awk '{print $2}' | head -3)
if [ -n "$DNS_SERVERS" ]; then
    echo " 설정된 DNS 서버:"
    echo "$DNS_SERVERS" | sed 's/^/   - /'
    for TARGET in $TARGETS; do
        HOST=$(echo "$TARGET" | cut -d: -f1)
        # IP가 아닌 호스트명만 테스트
        if ! echo "$HOST" | grep -qE "^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$"; then
            RESOLVED=$(getent hosts "$HOST" 2>/dev/null | awk '{print $1}' | head -1 || echo "FAIL")
            if [ "$RESOLVED" = "FAIL" ] || [ -z "$RESOLVED" ]; then
                echo " ${WARN} DNS 해석 실패: ${HOST}"
                [ $RESULT -lt 1 ] && RESULT=1
            else
                echo " ${OK} ${HOST} → ${RESOLVED}"
            fi
        fi
    done
else
    echo " ${WARN} DNS 서버 설정 없음"
    [ $RESULT -lt 1 ] && RESULT=1
fi

# ── 4. 라우팅 테이블 ─────────────────────────────────────
echo; echo "[$SEP] 4. 기본 게이트웨이"
GW=$(ip route show default 2>/dev/null | awk '/default/{print $3}' | head -1 || \
     route -n 2>/dev/null | awk '/^0.0.0.0/{print $2}' | head -1 || echo "N/A")
if [ "$GW" != "N/A" ] && [ -n "$GW" ]; then
    echo " ${OK} 기본 게이트웨이: ${GW}"
    GW_PING=$(ping -c 2 -W 2 "$GW" 2>/dev/null | grep "packet loss" | \
        grep -oP '\d+(?=% packet loss)' || echo 100)
    [ "${GW_PING:-100}" -lt 50 ] && echo " ${OK} 게이트웨이 응답 정상" || \
        echo " ${WARN} 게이트웨이 응답 없음"
else
    echo " ${WARN} 기본 게이트웨이를 찾을 수 없음"
    [ $RESULT -lt 1 ] && RESULT=1
fi

# ── 5. 네트워크 인터페이스 상태 ───────────────────────────
echo; echo "[$SEP] 5. 네트워크 인터페이스"
ip link show 2>/dev/null | awk '/^[0-9]+:/{
    name=$2; gsub(/:$/,"",name)
    if(name != "lo") {
        getline; state=($0 ~ /UP/) ? "UP" : "DOWN"
        printf "   %-15s %s\n", name, state
    }
}' | head -10

# ── 요약 ─────────────────────────────────────────────────
echo
echo "======================================================"
case $RESULT in
    0) echo " 최종 결과: ${OK}   네트워크 연결 정상" ;;
    1) echo " 최종 결과: ${WARN} 주의 항목 있음" ;;
    2) echo " 최종 결과: ${CRIT} 연결 실패 항목 있음" ;;
esac
echo " 점검 완료: $(date '+%Y-%m-%d %H:%M:%S')"
echo "======================================================"
exit $RESULT
