#!/bin/bash
# ============================================================
# GUARDiA SM | esb_check.sh
# 대상: ESB / MQ (ActiveMQ, IBM MQ, WSO2 ESB/MI)
# 파라미터: ESB_TYPE=activemq|ibmmq|wso2
#           ACTIVEMQ_HOME=/opt/activemq ACTIVEMQ_PORT=61616
#           ACTIVEMQ_CONSOLE=http://localhost:8161
#           IBMMQ_HOME=/opt/mqm MQ_QMGR=QM1 MQ_PORT=1414
#           WSO2_HOME=/opt/wso2 WSO2_PORT=8280 WSO2_MGMT_PORT=9443
#           QUEUE_DEPTH_WARN=1000
# ============================================================
set -euo pipefail
ESB_TYPE=${ESB_TYPE:-activemq}
ACTIVEMQ_HOME=${ACTIVEMQ_HOME:-/opt/activemq}
ACTIVEMQ_PORT=${ACTIVEMQ_PORT:-61616}
ACTIVEMQ_CONSOLE=${ACTIVEMQ_CONSOLE:-"http://localhost:8161"}
ACTIVEMQ_USER=${ACTIVEMQ_USER:-admin}
ACTIVEMQ_PASS=${ACTIVEMQ_PASS:-admin}
IBMMQ_HOME=${IBMMQ_HOME:-/opt/mqm}
MQ_QMGR=${MQ_QMGR:-QM1}
MQ_PORT=${MQ_PORT:-1414}
WSO2_HOME=${WSO2_HOME:-/opt/wso2}
WSO2_PORT=${WSO2_PORT:-8280}
WSO2_MGMT_PORT=${WSO2_MGMT_PORT:-9443}
QUEUE_DEPTH_WARN=${QUEUE_DEPTH_WARN:-1000}
OK="[OK]"; WARN="[WARN]"; CRIT="[CRIT]"
SEP="─────────────────────────────────────────"
RESULT=0

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

# ════════════════════════════════════════════
# ActiveMQ
# ════════════════════════════════════════════
check_activemq() {
    echo; echo "[$SEP] 1. ActiveMQ 프로세스"
    AMQ_PROC=$(pgrep -c "activemq" 2>/dev/null || echo 0)
    if [ "$AMQ_PROC" -gt 0 ]; then
        echo " ${OK} ActiveMQ 실행 중 (${AMQ_PROC}개)"
    else
        echo " ${CRIT} ActiveMQ 프로세스 없음"
        RESULT=2
    fi

    echo; echo "[$SEP] 2. 포트 리스닝"
    for PORT in $ACTIVEMQ_PORT 61613 61614; do
        ss -tlnp 2>/dev/null | grep -q ":${PORT} " && \
            echo " ${OK} 포트 ${PORT} LISTEN" || \
            echo " ${WARN} 포트 ${PORT} LISTEN 없음"
    done

    echo; echo "[$SEP] 3. 웹 콘솔 (Jolokia REST API)"
    if command -v curl &>/dev/null; then
        # 브로커 상태
        BROKER=$(curl -sk --max-time 5 \
            -u "${ACTIVEMQ_USER}:${ACTIVEMQ_PASS}" \
            "${ACTIVEMQ_CONSOLE}/api/jolokia/read/org.apache.activemq:type=Broker,brokerName=localhost/TotalEnqueueCount,TotalDequeueCount,TotalConsumerCount,TotalProducerCount" \
            2>/dev/null || echo "")
        if echo "$BROKER" | python3 -c "import sys,json; d=json.load(sys.stdin); \
            v=d.get('value',{}); \
            [print(f'  {k}: {val}') for k,val in v.items()]" 2>/dev/null; then
            echo " ${OK} 브로커 상태 정상"
        else
            echo " ${WARN} Jolokia API 응답 없음 (웹 콘솔 접근 불가)"
            [ $RESULT -lt 1 ] && RESULT=1
        fi

        # DLQ (Dead Letter Queue) 확인
        DLQ=$(curl -sk --max-time 5 \
            -u "${ACTIVEMQ_USER}:${ACTIVEMQ_PASS}" \
            "${ACTIVEMQ_CONSOLE}/api/jolokia/search/org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=ActiveMQ.DLQ" \
            2>/dev/null || echo "")
        if echo "$DLQ" | grep -q "DLQ"; then
            DLQ_DEPTH=$(curl -sk --max-time 5 \
                -u "${ACTIVEMQ_USER}:${ACTIVEMQ_PASS}" \
                "${ACTIVEMQ_CONSOLE}/api/jolokia/read/org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=ActiveMQ.DLQ/QueueSize" \
                2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('value',0))" 2>/dev/null || echo 0)
            if [ "${DLQ_DEPTH:-0}" -gt 0 ]; then
                echo " ${WARN} DLQ 메시지 ${DLQ_DEPTH}건"
                [ $RESULT -lt 1 ] && RESULT=1
            else
                echo " ${OK} DLQ 비어있음"
            fi
        fi
    fi

    echo; echo "[$SEP] 4. 로그 오류"
    for LOGDIR in "${ACTIVEMQ_HOME}/data" "${ACTIVEMQ_HOME}/logs"; do
        LOGFILE=$(ls -t "${LOGDIR}"/activemq.log 2>/dev/null | head -1 || echo "")
        if [ -n "$LOGFILE" ] && [ -r "$LOGFILE" ]; then
            ERR=$(tail -500 "$LOGFILE" | grep -cE "ERROR|FATAL|Exception" || echo 0)
            echo " 최근 오류: ${ERR}건 (${LOGFILE})"
            [ "$ERR" -gt 0 ] && tail -500 "$LOGFILE" | grep -E "ERROR|FATAL" | tail -5 | sed 's/^/   /'
            break
        fi
    done
}

# ════════════════════════════════════════════
# IBM MQ
# ════════════════════════════════════════════
check_ibmmq() {
    export PATH="${IBMMQ_HOME}/bin:${PATH}"

    echo; echo "[$SEP] 1. IBM MQ 프로세스"
    MQ_PROC=$(pgrep -c "amq[a-z]" 2>/dev/null || echo 0)
    if [ "$MQ_PROC" -gt 0 ]; then
        echo " ${OK} IBM MQ 실행 중 (${MQ_PROC}개)"
    else
        echo " ${CRIT} IBM MQ 프로세스 없음"
        RESULT=2
    fi

    echo; echo "[$SEP] 2. 큐 매니저 상태"
    if command -v dspmq &>/dev/null; then
        QMGR_STATUS=$(dspmq 2>/dev/null | grep "$MQ_QMGR" || echo "조회 실패")
        echo " ${QMGR_STATUS}"
        echo "$QMGR_STATUS" | grep -qi "running" && echo " ${OK} 큐 매니저 Running" || \
            { echo " ${CRIT} 큐 매니저 비정상"; RESULT=2; }
    fi

    echo; echo "[$SEP] 3. 큐 깊이"
    if command -v runmqsc &>/dev/null; then
        QUEUE_INFO=$(echo "DISPLAY QL(*) CURDEPTH" | runmqsc "$MQ_QMGR" 2>/dev/null | \
            grep "CURDEPTH" | awk '{print $0}' | head -20 || echo "")
        echo "$QUEUE_INFO" | sed 's/^/ /' | head -15
        DEEP=$(echo "$QUEUE_INFO" | awk -F'CURDEPTH\\(' '{print $2}' | tr -d ')' | \
            sort -rn | head -1 || echo 0)
        if [ "${DEEP:-0}" -gt "$QUEUE_DEPTH_WARN" ]; then
            echo " ${WARN} 최대 큐 깊이: ${DEEP}"
            [ $RESULT -lt 1 ] && RESULT=1
        else
            echo " ${OK} 큐 깊이 정상 (최대: ${DEEP})"
        fi
    fi

    echo; echo "[$SEP] 4. 채널 상태"
    if command -v runmqsc &>/dev/null; then
        CH_STATUS=$(echo "DISPLAY CHSTATUS(*)" | runmqsc "$MQ_QMGR" 2>/dev/null | \
            grep "CHSTATUS" | head -10 || echo "채널 없음")
        echo "$CH_STATUS" | sed 's/^/ /'
    fi
}

# ════════════════════════════════════════════
# WSO2 ESB / Micro Integrator
# ════════════════════════════════════════════
check_wso2() {
    echo; echo "[$SEP] 1. WSO2 프로세스"
    WSO2_PROC=$(pgrep -f "wso2\|carbon" 2>/dev/null | wc -l || echo 0)
    if [ "$WSO2_PROC" -gt 0 ]; then
        echo " ${OK} WSO2 실행 중 (${WSO2_PROC}개)"
    else
        echo " ${CRIT} WSO2 프로세스 없음"
        RESULT=2
    fi

    echo; echo "[$SEP] 2. 포트 리스닝"
    for PORT in $WSO2_PORT $WSO2_MGMT_PORT; do
        ss -tlnp 2>/dev/null | grep -q ":${PORT} " && \
            echo " ${OK} 포트 ${PORT} LISTEN" || \
            echo " ${WARN} 포트 ${PORT} LISTEN 없음"
    done

    echo; echo "[$SEP] 3. 관리 콘솔 응답"
    if command -v curl &>/dev/null; then
        HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" \
            --max-time 10 "https://localhost:${WSO2_MGMT_PORT}/carbon/admin/login.jsp" \
            2>/dev/null || echo "ERR")
        if echo "$HTTP_CODE" | grep -qE "^[23]"; then
            echo " ${OK} 관리 콘솔 응답: ${HTTP_CODE}"
        else
            echo " ${WARN} 관리 콘솔 응답: ${HTTP_CODE}"
            [ $RESULT -lt 1 ] && RESULT=1
        fi
    fi

    echo; echo "[$SEP] 4. WSO2 로그 오류"
    for LOGDIR in "${WSO2_HOME}/repository/logs" "${WSO2_HOME}/logs"; do
        if [ -d "$LOGDIR" ]; then
            LOGFILE=$(ls -t "${LOGDIR}"/wso2*.log "${LOGDIR}"/carbon*.log 2>/dev/null | head -1 || echo "")
            if [ -n "$LOGFILE" ] && [ -r "$LOGFILE" ]; then
                ERR=$(tail -1000 "$LOGFILE" | grep -cE "ERROR|FATAL" || echo 0)
                echo " 최근 오류: ${ERR}건"
                [ "$ERR" -gt 0 ] && tail -1000 "$LOGFILE" | grep -E "ERROR|FATAL" | tail -5 | sed 's/^/   /'
            fi
            break
        fi
    done
}

# 타입별 실행
case "${ESB_TYPE,,}" in
    activemq)  check_activemq ;;
    ibmmq|mq)  check_ibmmq ;;
    wso2)      check_wso2 ;;
    *)
        echo " ${WARN} 알 수 없는 ESB_TYPE: ${ESB_TYPE}"
        echo " 지원: activemq, ibmmq, wso2"
        [ $RESULT -lt 1 ] && RESULT=1
        ;;
esac

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