#!/bin/bash
# ============================================================
# GUARDiA SM | was_jeus_sm.sh
# 대상: JEUS (TmaxSoft) WAS
# 파라미터: JEUS_HOME=/opt/jeus JEUS_DOMAIN=domain1
#           JEUS_PORT=9736 APP_PORT=8080 JEUS_ADMIN=administrator
#           JEUS_PASS=jeusadmin HEALTH_URL=http://localhost:8080/health
# ============================================================
set -euo pipefail
JEUS_HOME=${JEUS_HOME:-/opt/jeus}
JEUS_DOMAIN=${JEUS_DOMAIN:-domain1}
JEUS_PORT=${JEUS_PORT:-9736}
APP_PORT=${APP_PORT:-8080}
JEUS_ADMIN=${JEUS_ADMIN:-administrator}
JEUS_PASS=${JEUS_PASS:-jeusadmin}
HEALTH_URL=${HEALTH_URL:-"http://localhost:${APP_PORT}/health"}
OK="[OK]"; WARN="[WARN]"; CRIT="[CRIT]"
SEP="─────────────────────────────────────────"
RESULT=0

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

# ── 1. 프로세스 ───────────────────────────────────────────
echo; echo "[$SEP] 1. JEUS 프로세스"
JEUS_PID=$(pgrep -f "jeus\|DomainAdminServer" 2>/dev/null | head -1 || echo "")
JEUS_PROC_COUNT=$(pgrep -c "jeus" 2>/dev/null || echo 0)
if [ "$JEUS_PROC_COUNT" -gt 0 ]; then
    echo " ${OK} JEUS 프로세스 실행 중 (${JEUS_PROC_COUNT}개)"
    ps aux | grep jeus | grep -v grep | awk \
        '{printf " PID:%-8s CPU:%-6s MEM:%-6s\n",$2,$3,$4}' | head -5
else
    echo " ${CRIT} JEUS 프로세스 없음"
    RESULT=2
fi

# ── 2. 포트 리스닝 ────────────────────────────────────────
echo; echo "[$SEP] 2. 포트 리스닝"
for PORT in $JEUS_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. jeusadmin 상태 조회 ────────────────────────────────
echo; echo "[$SEP] 3. jeusadmin 서버 상태"
JEUSADMIN="${JEUS_HOME}/bin/jeusadmin"
if [ -x "$JEUSADMIN" ]; then
    # Non-interactive 상태 조회
    JSTAT=$(echo -e "si\nls\nq" | \
        "$JEUSADMIN" -u "${JEUS_ADMIN}" -p "${JEUS_PASS}" \
        -host localhost -port "${JEUS_PORT}" 2>/dev/null | \
        grep -v "^$\|jeusadmin>" | head -30 || echo "조회 실패")
    echo "$JSTAT" | sed 's/^/ /'
else
    echo " ${WARN} jeusadmin 없음: ${JEUSADMIN}"
    [ $RESULT -lt 1 ] && RESULT=1
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 "$JEUS_PID" ]; then
    RSS_MB=$(awk '/VmRSS/{print $2}' /proc/${JEUS_PID}/status 2>/dev/null | \
        awk '{printf "%d", $1/1024}' || echo "N/A")
    THREAD=$(ls /proc/${JEUS_PID}/task 2>/dev/null | wc -l || echo 0)
    echo " RSS 메모리: ${RSS_MB} MB"
    echo " 스레드 수: ${THREAD}"
fi

# ── 6. 로그 에러 ─────────────────────────────────────────
echo; echo "[$SEP] 6. JEUS 로그 오류"
for LOGDIR in "${JEUS_HOME}/domains/${JEUS_DOMAIN}/servers/server1/logs" \
              "${JEUS_HOME}/logs" "${JEUS_HOME}/domain/logs"; do
    if [ -d "$LOGDIR" ]; then
        LOGFILE=$(ls -t "${LOGDIR}"/*.log 2>/dev/null | head -1 || echo "")
        if [ -n "$LOGFILE" ] && [ -r "$LOGFILE" ]; then
            ERR_CNT=$(tail -2000 "$LOGFILE" | grep -c "ERROR\|FATAL\|Exception" || echo 0)
            echo " 최근 오류 수: ${ERR_CNT} (${LOGFILE})"
            [ "$ERR_CNT" -gt 0 ] && tail -2000 "$LOGFILE" | grep -E "ERROR|FATAL|Exception" | \
                tail -5 | sed 's/^/   /'
        fi
        break
    fi
done

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