#!/bin/bash
# ============================================================
# GUARDiA SM | was_jboss_sm.sh
# 대상: JBoss / WildFly WAS
# 파라미터: JBOSS_HOME=/opt/wildfly APP_PORT=8080
#           MGMT_PORT=9990 MGMT_USER=admin MGMT_PASS=admin
#           HEALTH_URL=http://localhost:8080/health
# ============================================================
set -euo pipefail
JBOSS_HOME=${JBOSS_HOME:-/opt/wildfly}
APP_PORT=${APP_PORT:-8080}
MGMT_PORT=${MGMT_PORT:-9990}
MGMT_USER=${MGMT_USER:-admin}
MGMT_PASS=${MGMT_PASS:-admin}
HEALTH_URL=${HEALTH_URL:-"http://localhost:${APP_PORT}/health"}
OK="[OK]"; WARN="[WARN]"; CRIT="[CRIT]"
SEP="─────────────────────────────────────────"
RESULT=0

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

# ── 1. 프로세스 ───────────────────────────────────────────
echo; echo "[$SEP] 1. JBoss/WildFly 프로세스"
JBOSS_PID=$(pgrep -f "jboss-modules\|wildfly\|standalone.sh" 2>/dev/null | head -1 || echo "")
if [ -n "$JBOSS_PID" ]; then
    echo " ${OK} JBoss/WildFly 실행 중 (PID: ${JBOSS_PID})"
    START=$(ps -p "$JBOSS_PID" -o lstart= 2>/dev/null || echo "N/A")
    echo " 시작 시각: ${START}"
else
    echo " ${CRIT} JBoss/WildFly 프로세스 없음"
    RESULT=2
fi

# ── 2. 포트 ───────────────────────────────────────────────
echo; echo "[$SEP] 2. 포트 리스닝"
for PORT in $APP_PORT $MGMT_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. Management API 서버 상태 ───────────────────────────
echo; echo "[$SEP] 3. Management API 서버 상태"
if command -v curl &>/dev/null; then
    MGMT_RESP=$(curl -sk --max-time 5 -u "${MGMT_USER}:${MGMT_PASS}" \
        "http://localhost:${MGMT_PORT}/management?operation=attribute&name=server-state" \
        2>/dev/null || echo "")
    if echo "$MGMT_RESP" | grep -qi '"running"'; then
        echo " ${OK} 서버 상태: running"
    elif [ -n "$MGMT_RESP" ]; then
        echo " ${WARN} 서버 상태: ${MGMT_RESP}"
        [ $RESULT -lt 1 ] && RESULT=1
    else
        echo " ${WARN} Management 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. 데이터소스 상태 ────────────────────────────────────
echo; echo "[$SEP] 5. 데이터소스 (Management API)"
if command -v curl &>/dev/null; then
    DS_RESP=$(curl -sk --max-time 5 -u "${MGMT_USER}:${MGMT_PASS}" \
        "http://localhost:${MGMT_PORT}/management/subsystem/datasources/data-source?recursive=true" \
        2>/dev/null | python3 -m json.tool 2>/dev/null | grep '"connection-url"' | head -5 || echo "")
    if [ -n "$DS_RESP" ]; then
        echo " 데이터소스 연결 URL:"
        echo "$DS_RESP" | sed 's/^/   /'
    else
        echo " ${WARN} 데이터소스 조회 불가"
    fi
fi

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

# ── 7. 배포 앱 목록 ──────────────────────────────────────
echo; echo "[$SEP] 7. 배포 앱"
DEPLOY_DIR="${JBOSS_HOME}/standalone/deployments"
if [ -d "$DEPLOY_DIR" ]; then
    echo " 배포 목록 (${DEPLOY_DIR}):"
    ls "$DEPLOY_DIR" 2>/dev/null | grep -v "\.failed\|\.undeployed" | sed 's/^/   - /'
    FAILED=$(ls "$DEPLOY_DIR"/*.failed 2>/dev/null | wc -l || echo 0)
    [ "$FAILED" -gt 0 ] && echo " ${CRIT} 배포 실패 항목: ${FAILED}개" && RESULT=2
else
    echo " ${WARN} deployments 디렉터리 없음"
fi

# ── 8. 서버 로그 에러 ─────────────────────────────────────
echo; echo "[$SEP] 8. 서버 로그 오류"
SERVER_LOG="${JBOSS_HOME}/standalone/log/server.log"
if [ -r "$SERVER_LOG" ]; then
    ERR_COUNT=$(tail -2000 "$SERVER_LOG" | grep -c "ERROR\|FATAL" || echo 0)
    if [ "$ERR_COUNT" -gt 0 ]; then
        echo " ${WARN} 최근 오류 ${ERR_COUNT}건:"
        tail -2000 "$SERVER_LOG" | grep -E "ERROR|FATAL" | tail -5 | sed 's/^/   /'
        [ $RESULT -lt 1 ] && RESULT=1
    else
        echo " ${OK} 최근 오류 없음"
    fi
else
    echo " ${WARN} 서버 로그 없음: ${SERVER_LOG}"
fi

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