#!/usr/bin/env bash
# =============================================================================
# WAS 재기동 스크립트
# Jenkins Stage 6: WAS Restart에서 호출
# 지원: Tomcat, JBoss/WildFly, JEUS, WebLogic, Node.js(pm2/systemd)
# =============================================================================
set -euo pipefail

SERVER=""
SSH_KEY=""
SSH_USER="deploy"
SSH_PORT="${SSH_PORT:-22}"
WAS_TYPE="${WAS_TYPE:-tomcat}"
WAS_SERVICE="${WAS_SERVICE:-}"   # systemd 서비스명 (빈칸이면 자동 감지)
STARTUP_WAIT="${STARTUP_WAIT:-60}"  # 기동 대기 시간 (초)
LOG_DIR="${WORKSPACE:-/tmp}/build-logs"
RESTART_LOG="${LOG_DIR}/was-restart-$(date +%Y%m%d-%H%M%S).log"

GREEN='\033[0;32m'; RED='\033[0;31m'; YELLOW='\033[1;33m'; NC='\033[0m'
log()  { echo -e "${GREEN}[WAS]${NC} $*" | tee -a "${RESTART_LOG}"; }
err()  { echo -e "${RED}[ERROR]${NC} $*" | tee -a "${RESTART_LOG}"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*" | tee -a "${RESTART_LOG}"; }

mkdir -p "${LOG_DIR}"

while [[ $# -gt 0 ]]; do
    case $1 in
        --server)    SERVER="$2";        shift 2 ;;
        --ssh-key)   SSH_KEY="$2";       shift 2 ;;
        --ssh-user)  SSH_USER="$2";      shift 2 ;;
        --was-type)  WAS_TYPE="$2";      shift 2 ;;
        --service)   WAS_SERVICE="$2";   shift 2 ;;
        --wait)      STARTUP_WAIT="$2";  shift 2 ;;
        *) shift ;;
    esac
done

[[ -z "${SERVER}" ]]  && { err "--server 파라미터가 필요합니다"; exit 1; }
[[ -z "${SSH_KEY}" ]] && { err "--ssh-key 파라미터가 필요합니다"; exit 1; }

chmod 600 "${SSH_KEY}"
TARGET_HOST="${TARGET_HOST:-${SERVER}}"
SSH_OPTS="-i ${SSH_KEY} -p ${SSH_PORT} -o StrictHostKeyChecking=no -o ConnectTimeout=10"
SSH_CMD="ssh ${SSH_OPTS} ${SSH_USER}@${TARGET_HOST}"

log "WAS 재기동: ${WAS_TYPE} @ ${TARGET_HOST}"

# ── Tomcat ────────────────────────────────────────────────────────────────────
restart_tomcat() {
    local service="${WAS_SERVICE:-tomcat9}"
    # 서비스명 자동 감지 (tomcat9 / tomcat10 / tomcat)
    local actual_service
    actual_service=$(${SSH_CMD} "
        for s in tomcat9 tomcat10 tomcat; do
            systemctl list-units --type=service | grep -q \"\$s\" && echo \"\$s\" && break
        done
    " 2>/dev/null || echo "${service}")

    log "Tomcat 서비스 재기동: ${actual_service}"
    ${SSH_CMD} "sudo systemctl restart '${actual_service}'"

    # 기동 확인
    local elapsed=0
    while [[ ${elapsed} -lt ${STARTUP_WAIT} ]]; do
        if ${SSH_CMD} "sudo systemctl is-active --quiet '${actual_service}'" 2>/dev/null; then
            log "Tomcat 기동 완료 (${elapsed}초)"
            return 0
        fi
        sleep 3
        elapsed=$((elapsed + 3))
    done
    err "Tomcat 기동 타임아웃 (${STARTUP_WAIT}초)"
    ${SSH_CMD} "sudo systemctl status '${actual_service}'" 2>&1 | tee -a "${RESTART_LOG}" || true
    exit 1
}

# ── JBoss / WildFly ────────────────────────────────────────────────────────────
restart_jboss() {
    local service="${WAS_SERVICE:-jboss}"
    local actual_service
    actual_service=$(${SSH_CMD} "
        for s in jboss wildfly eap7 jboss-eap; do
            systemctl list-units --type=service | grep -q \"\$s\" && echo \"\$s\" && break
        done
    " 2>/dev/null || echo "${service}")

    log "JBoss/WildFly 서비스 재기동: ${actual_service}"
    ${SSH_CMD} "sudo systemctl restart '${actual_service}'"

    local elapsed=0
    while [[ ${elapsed} -lt ${STARTUP_WAIT} ]]; do
        if ${SSH_CMD} "sudo systemctl is-active --quiet '${actual_service}'" 2>/dev/null; then
            log "JBoss 기동 완료 (${elapsed}초)"
            return 0
        fi
        sleep 5
        elapsed=$((elapsed + 5))
    done
    err "JBoss 기동 타임아웃"
    exit 1
}

# ── JEUS ──────────────────────────────────────────────────────────────────────
restart_jeus() {
    local jeus_home="${JEUS_HOME:-/opt/jeus8}"
    local domain="${JEUS_DOMAIN:-domain1}"
    local server="${JEUS_SERVER:-server1}"
    local admin_port="${JEUS_ADMIN_PORT:-9736}"

    log "JEUS 서버 재기동: ${domain}/${server}"
    ${SSH_CMD} "
        export JEUS_HOME='${jeus_home}'
        export PATH=\"\${JEUS_HOME}/bin:\${PATH}\"

        # 서버 중지
        jeusadmin -host localhost:${admin_port} -u administrator \
            'stopServer ${server}' 2>/dev/null || true

        sleep 5

        # 서버 시작
        startManagedServer -domain '${domain}' -server '${server}' &
    "

    local elapsed=0
    while [[ ${elapsed} -lt ${STARTUP_WAIT} ]]; do
        if ${SSH_CMD} "
            export JEUS_HOME='${jeus_home}'
            jeusadmin -host localhost:${admin_port} -u administrator \
                'serverinfo ${server}' 2>/dev/null | grep -q 'RUNNING'
        " 2>/dev/null; then
            log "JEUS 기동 완료 (${elapsed}초)"
            return 0
        fi
        sleep 5
        elapsed=$((elapsed + 5))
    done
    err "JEUS 기동 타임아웃"
    exit 1
}

# ── WebLogic ──────────────────────────────────────────────────────────────────
restart_weblogic() {
    local wl_home="${WL_HOME:-/opt/oracle/wlserver}"
    local domain_home="${WL_DOMAIN_HOME:-/opt/oracle/domains/base_domain}"
    local server="${WL_SERVER:-ManagedServer1}"

    log "WebLogic 서버 재기동: ${server}"
    ${SSH_CMD} "
        # 서버 중지
        '${domain_home}/bin/stopWebLogic.sh' '${server}' 2>/dev/null || true
        sleep 5
        # 서버 시작
        nohup '${domain_home}/bin/startManagedWebLogic.sh' \
            '${server}' 'http://localhost:7001' &
    "

    local elapsed=0
    while [[ ${elapsed} -lt ${STARTUP_WAIT} ]]; do
        if ${SSH_CMD} "
            curl -sf 'http://localhost:7001/management/tenant-monitoring/servers/${server}' \
                2>/dev/null | grep -q '\"state\":\"RUNNING\"'
        " 2>/dev/null; then
            log "WebLogic 기동 완료 (${elapsed}초)"
            return 0
        fi
        sleep 5
        elapsed=$((elapsed + 5))
    done
    err "WebLogic 기동 타임아웃"
    exit 1
}

# ── Node.js (pm2 또는 systemd) ────────────────────────────────────────────────
restart_nodejs() {
    local service="${WAS_SERVICE:-}"
    local app_name="${NODE_APP_NAME:-app}"

    log "Node.js 재기동..."
    ${SSH_CMD} "
        if command -v pm2 &>/dev/null; then
            pm2 restart '${app_name}' || pm2 reload '${app_name}'
        elif systemctl list-units --type=service | grep -q '${service:-nodejs}'; then
            sudo systemctl restart '${service:-nodejs}'
        else
            echo '재기동 방법을 찾을 수 없습니다. PM2 또는 systemd 서비스가 필요합니다.'
            exit 1
        fi
    "
    sleep 3
    log "Node.js 재기동 완료"
}

# ── 메인 ─────────────────────────────────────────────────────────────────────
main() {
    log "=== WAS 재기동 시작: $(date) ==="
    case "${WAS_TYPE,,}" in
        tomcat|tomcat9|tomcat10) restart_tomcat  ;;
        jboss|wildfly|eap)       restart_jboss   ;;
        jeus|jeus8|jeus9)        restart_jeus    ;;
        weblogic|wls)            restart_weblogic ;;
        nodejs|node|pm2)         restart_nodejs   ;;
        systemd)
            log "systemd 서비스 재기동: ${WAS_SERVICE}"
            ${SSH_CMD} "sudo systemctl restart '${WAS_SERVICE}'"
            ;;
        *)
            err "지원하지 않는 WAS 종류: ${WAS_TYPE}"
            exit 1
            ;;
    esac
    log "=== WAS 재기동 완료 ==="
}

main "$@"
