#!/bin/bash
# ============================================================
# GUARDiA SM | db_tibero_sm.sh
# 대상: Tibero RDBMS (TmaxSoft)
# 파라미터: TB_HOME=/opt/tibero TB_SID=tibero
#           TB_PORT=8629 TB_USER=sys TB_PASS=tibero
#           TS_WARN=80 SESSION_WARN=80
# ============================================================
set -euo pipefail
TB_HOME=${TB_HOME:-/opt/tibero}
TB_SID=${TB_SID:-tibero}
TB_PORT=${TB_PORT:-8629}
TB_USER=${TB_USER:-sys}
TB_PASS=${TB_PASS:-tibero}
TS_WARN=${TS_WARN:-80}
SESSION_WARN=${SESSION_WARN:-80}
OK="[OK]"; WARN="[WARN]"; CRIT="[CRIT]"
SEP="─────────────────────────────────────────"
RESULT=0
export TB_HOME TB_SID
export PATH="${TB_HOME}/bin:${PATH}"
export LD_LIBRARY_PATH="${TB_HOME}/lib:${LD_LIBRARY_PATH:-}"

# tbsql 헬퍼
_tbsql() {
    tbsql -s "${TB_USER}/${TB_PASS}" <<EOF 2>/dev/null
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
$1
EXIT;
EOF
}

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

# ── 1. 프로세스 ───────────────────────────────────────────
echo; echo "[$SEP] 1. Tibero 프로세스"
TB_PROC=$(pgrep -c "tbsvr\|tblistener\|tbagt" 2>/dev/null || echo 0)
TB_SRV=$(pgrep -c "tbsvr" 2>/dev/null || echo 0)
if [ "$TB_SRV" -gt 0 ]; then
    echo " ${OK} Tibero 서버 실행 중 (${TB_SRV}개)"
else
    echo " ${CRIT} Tibero 서버(tbsvr) 프로세스 없음"
    RESULT=2
fi
echo " 전체 Tibero 프로세스: ${TB_PROC}개"

# ── 2. tblistener 상태 ────────────────────────────────────
echo; echo "[$SEP] 2. tblistener 상태"
LSNR_PROC=$(pgrep -c "tblistener" 2>/dev/null || echo 0)
if [ "$LSNR_PROC" -gt 0 ]; then
    echo " ${OK} tblistener 실행 중"
else
    echo " ${CRIT} tblistener 없음"
    RESULT=2
fi

# 포트 리스닝
if ss -tlnp 2>/dev/null | grep -q ":${TB_PORT} "; then
    echo " ${OK} 포트 ${TB_PORT} LISTEN"
else
    echo " ${CRIT} 포트 ${TB_PORT} LISTEN 없음"
    RESULT=2
fi

# ── 3. tbsql 접속 + DB 상태 ──────────────────────────────
echo; echo "[$SEP] 3. DB 접속 및 인스턴스 상태"
if command -v tbsql &>/dev/null; then
    DB_STATUS=$(_tbsql "SELECT status FROM v\$instance;" 2>/dev/null | tr -d ' ')
    if echo "$DB_STATUS" | grep -qi "OPEN"; then
        echo " ${OK} DB 상태: OPEN"
        VERSION=$(_tbsql "SELECT version FROM v\$instance;" 2>/dev/null | head -1 | tr -d ' ')
        echo " Tibero 버전: ${VERSION}"
    elif [ -n "$DB_STATUS" ]; then
        echo " ${WARN} DB 상태: ${DB_STATUS}"
        [ $RESULT -lt 1 ] && RESULT=1
    else
        echo " ${CRIT} DB 접속 실패"
        RESULT=2
    fi
else
    echo " ${WARN} tbsql 없음: ${TB_HOME}/bin/tbsql"
    [ $RESULT -lt 1 ] && RESULT=1
fi

# ── 4. 세션 현황 ─────────────────────────────────────────
echo; echo "[$SEP] 4. 세션 현황"
if command -v tbsql &>/dev/null && [ "$RESULT" -lt 2 ]; then
    SESS_INFO=$(_tbsql "
        SELECT 'TOTAL:'||count(*)||
               ' ACTIVE:'||sum(CASE WHEN status='ACTIVE' THEN 1 ELSE 0 END)||
               ' INACTIVE:'||sum(CASE WHEN status='INACTIVE' THEN 1 ELSE 0 END)
        FROM v\$session WHERE type='USER';" 2>/dev/null | tr -d ' ')
    echo " ${SESS_INFO}"
    MAX_SESS=$(_tbsql "SELECT value FROM v\$parameter WHERE name='max_session_count';" \
        2>/dev/null | tr -d ' ' || echo 100)
    CURR_SESS=$(_tbsql "SELECT count(*) FROM v\$session;" 2>/dev/null | tr -d ' ' || echo 0)
    if [ -n "$MAX_SESS" ] && [ "$MAX_SESS" -gt 0 ]; then
        SESS_PCT=$(( CURR_SESS * 100 / MAX_SESS ))
        [ "$SESS_PCT" -ge "$SESSION_WARN" ] && \
            echo " ${WARN} 세션 사용률 ${SESS_PCT}% (${CURR_SESS}/${MAX_SESS})" && \
            [ $RESULT -lt 1 ] && RESULT=1 || \
            echo " ${OK} 세션 ${CURR_SESS}/${MAX_SESS} (${SESS_PCT}%)"
    fi
fi

# ── 5. 테이블스페이스 사용률 ─────────────────────────────
echo; echo "[$SEP] 5. 테이블스페이스 사용률"
if command -v tbsql &>/dev/null && [ "$RESULT" -lt 2 ]; then
    TS_INFO=$(_tbsql "
        SELECT df.tablespace_name,
               round(df.total_mb,1)||'MB' AS total,
               round(df.total_mb - nvl(fs.free_mb,0),1)||'MB' AS used,
               round((df.total_mb - nvl(fs.free_mb,0))*100/df.total_mb,1)||'%' AS pct_used
        FROM (SELECT tablespace_name, sum(bytes)/1048576 total_mb
              FROM dba_data_files GROUP BY tablespace_name) df
        LEFT JOIN (SELECT tablespace_name, sum(bytes)/1048576 free_mb
                   FROM dba_free_space GROUP BY tablespace_name) fs
          ON df.tablespace_name = fs.tablespace_name
        ORDER BY 4 DESC;" 2>/dev/null | sed 's/^/ /' || echo " 조회 실패")
    echo "$TS_INFO"
fi

# ── 6. 알람 로그 ─────────────────────────────────────────
echo; echo "[$SEP] 6. 알람 로그 오류"
for LOGPATH in "${TB_HOME}/instance/${TB_SID}/log/slog/sys.log" \
               "${TB_HOME}/log/slog/sys.log" \
               "${TB_HOME}/logs/${TB_SID}.log"; do
    if [ -r "$LOGPATH" ]; then
        ERR_CNT=$(tail -500 "$LOGPATH" | grep -ciE "error|fatal|ORA-|TBR-" || echo 0)
        echo " 최근 오류 수: ${ERR_CNT} (${LOGPATH})"
        tail -500 "$LOGPATH" | grep -iE "ERROR|FATAL|ORA-|TBR-" | tail -5 | sed 's/^/   /' || true
        [ "$ERR_CNT" -gt 5 ] && [ $RESULT -lt 1 ] && RESULT=1
        break
    fi
done

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