#!/bin/bash
# ============================================================
# GUARDiA SM | was_weblogic_sm.sh
# 대상: Oracle WebLogic Server
# 파라미터: WL_HOME=/opt/oracle/middleware/wlserver
#           DOMAIN_HOME=/opt/oracle/domains/base_domain
#           ADMIN_PORT=7001 APP_PORT=7003
#           WL_USER=weblogic WL_PASS=weblogic1
#           HEALTH_URL=http://localhost:7003/health
# ============================================================
set -euo pipefail
WL_HOME=${WL_HOME:-/opt/oracle/middleware/wlserver}
DOMAIN_HOME=${DOMAIN_HOME:-/opt/oracle/domains/base_domain}
ADMIN_PORT=${ADMIN_PORT:-7001}
APP_PORT=${APP_PORT:-7003}
WL_USER=${WL_USER:-weblogic}
WL_PASS=${WL_PASS:-weblogic1}
HEALTH_URL=${HEALTH_URL:-"http://localhost:${APP_PORT}/health"}
OK="[OK]"; WARN="[WARN]"; CRIT="[CRIT]"
SEP="─────────────────────────────────────────"
RESULT=0

echo "======================================================"
echo " GUARDiA SM 점검 | Oracle WebLogic | $(hostname -s)"
echo " 점검 시각: $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "======================================================"

# ── 1. 프로세스 ───────────────────────────────────────────
echo; echo "[$SEP] 1. WebLogic 프로세스"
WL_PROC=$(pgrep -f "weblogic.Server\|AdminServer\|ManagedServer" 2>/dev/null | wc -l || echo 0)
ADMIN_PID=$(pgrep -f "AdminServer" 2>/dev/null | head -1 || echo "")
if [ "$WL_PROC" -gt 0 ]; then
    echo " ${OK} WebLogic 프로세스 실행 중 (${WL_PROC}개)"
    [ -n "$ADMIN_PID" ] && echo " AdminServer PID: ${ADMIN_PID}"
else
    echo " ${CRIT} WebLogic 프로세스 없음"
    RESULT=2
fi

# ── 2. 포트 리스닝 ────────────────────────────────────────
echo; echo "[$SEP] 2. 포트 리스닝"
for PORT in $ADMIN_PORT $APP_PORT; do
    if ss -tlnp 2>/dev/null | grep -q ":${PORT} "; then
        echo " ${OK} 포트 ${PORT} LISTEN"
    else
        echo " ${WARN} 포트 ${PORT} LISTEN 없음"
        [ $RESULT -lt 1 ] && RESULT=1
    fi
done

# ── 3. AdminServer REST API 상태 ─────────────────────────
echo; echo "[$SEP] 3. AdminServer 상태 (REST)"
if command -v curl &>/dev/null; then
    WL_STATE=$(curl -sk --max-time 5 \
        -u "${WL_USER}:${WL_PASS}" \
        "http://localhost:${ADMIN_PORT}/management/weblogic/latest/domainRuntime/serverLifeCycleRuntimes?fields=name,state" \
        2>/dev/null | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    items = d.get('items', d if isinstance(d, list) else [])
    for s in items[:5]:
        print(f\"  {s.get('name','?'):20s} {s.get('state','?')}\")
except: pass" 2>/dev/null || echo "")
    if [ -n "$WL_STATE" ]; then
        echo " 서버 상태:"
        echo "$WL_STATE"
    else
        echo " ${WARN} REST API 응답 없음 (인증/포트 확인 필요)"
        [ $RESULT -lt 1 ] && RESULT=1
    fi
fi

# ── 4. 헬스체크 ───────────────────────────────────────────
echo; echo "[$SEP] 4. 애플리케이션 헬스체크"
if command -v curl &>/dev/null; then
    HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" \
        --max-time 10 "${HEALTH_URL}" 2>/dev/null || echo "ERR")
    RESP_TIME=$(curl -sk -o /dev/null -w "%{time_total}" \
        --max-time 10 "${HEALTH_URL}" 2>/dev/null || echo "N/A")
    if echo "$HTTP_CODE" | grep -qE "^[23]"; then
        echo " ${OK} HTTP ${HTTP_CODE} — ${RESP_TIME}s"
    elif [ "$HTTP_CODE" = "ERR" ]; then
        echo " ${CRIT} 헬스체크 실패"
        RESULT=2
    else
        echo " ${WARN} HTTP ${HTTP_CODE}"
        [ $RESULT -lt 1 ] && RESULT=1
    fi
fi

# ── 5. JVM 메모리 ─────────────────────────────────────────
echo; echo "[$SEP] 5. JVM 메모리"
if [ -n "$ADMIN_PID" ]; then
    RSS_MB=$(awk '/VmRSS/{print $2}' /proc/${ADMIN_PID}/status 2>/dev/null | \
        awk '{printf "%d", $1/1024}' || echo "N/A")
    THREAD=$(ls /proc/${ADMIN_PID}/task 2>/dev/null | wc -l || echo 0)
    echo " AdminServer RSS: ${RSS_MB} MB"
    echo " AdminServer 스레드: ${THREAD}"
fi

# ── 6. 도메인 로그 오류 ──────────────────────────────────
echo; echo "[$SEP] 6. 도메인 로그 오류"
DOMAIN_LOG="${DOMAIN_HOME}/servers/AdminServer/logs/AdminServer.log"
if [ -r "$DOMAIN_LOG" ]; then
    ERR_CNT=$(tail -2000 "$DOMAIN_LOG" | grep -c "<Error>\|<Critical>\|<Emergency>" || echo 0)
    echo " 최근 오류 수: ${ERR_CNT}"
    [ "$ERR_CNT" -gt 0 ] && \
        tail -2000 "$DOMAIN_LOG" | grep -E "<Error>|<Critical>" | tail -5 | sed 's/^/   /' && \
        [ $RESULT -lt 1 ] && RESULT=1
    echo " ${OK} 로그 점검 완료"
else
    echo " ${WARN} 도메인 로그 없음: ${DOMAIN_LOG}"
fi

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