<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ page import="java.lang.reflect.Method" %>
<%@ page import="org.apache.commons.lang3.StringUtils" %>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager" %>
<%!
    // 최소 HTML 이스케이프 (진단 페이지 XSS 방지)
    private String esc(String s) {
        if (s == null) return "";
        StringBuilder b = new StringBuilder(s.length() + 16);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '&':  b.append("&amp;");  break;
                case '<':  b.append("&lt;");   break;
                case '>':  b.append("&gt;");   break;
                case '"':  b.append("&quot;"); break;
                case '\'': b.append("&#39;");  break;
                default:   b.append(c);
            }
        }
        return b.toString();
    }
%>
<%
    // 로그인 사용자만 접근 — real 모드에서 운영 키 암복호화 오라클이 되지 않도록 보호
    if (StringUtils.isBlank(SessionManager.getUserId(request))
            && StringUtils.isBlank(SessionManager.getRoleIdString(request))) {
        response.sendRedirect(request.getContextPath() + "/loginForm.do");
        return;
    }

    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "0");
    request.setCharacterEncoding("utf-8");

    String op    = request.getParameter("op");
    String input = request.getParameter("input");
    boolean run  = request.getParameter("run") != null;
    if (op == null)    op = "encrypt";
    if (input == null) input = "";

    String mode     = "UNKNOWN";
    String revision = "-";
    String returnCode = "-";
    String result   = "";
    String error    = "";
    boolean loaded  = false;

    try {
        Class<?> cls = Class.forName("com.eactive.ext.djb.DamoManager");
        Object damo  = cls.getMethod("getInstance").invoke(null);
        loaded = true;

        boolean bypass = (Boolean) cls.getMethod("isBypassMode").invoke(damo);
        boolean fake   = (Boolean) cls.getMethod("isFakeMode").invoke(damo);
        mode       = bypass ? "BYPASS" : (fake ? "FAKE" : "REAL");
        revision   = String.valueOf(cls.getMethod("getRevision").invoke(damo));
        returnCode = String.valueOf(cls.getMethod("getReturnCode").invoke(damo));

        if (run) {
            if ("encrypt".equals(op)) {
                result = (String) cls.getMethod("encrypt", String.class).invoke(damo, input);
            } else if ("decrypt".equals(op)) {
                result = (String) cls.getMethod("decrypt", String.class).invoke(damo, input);
            } else if ("sha256".equals(op)) {
                int t = cls.getField("SHA256").getInt(null);
                result = (String) cls.getMethod("hash", int.class, String.class).invoke(damo, t, input);
            } else if ("sha512".equals(op)) {
                int t = cls.getField("SHA512").getInt(null);
                result = (String) cls.getMethod("hash", int.class, String.class).invoke(damo, t, input);
            } else {
                error = "알 수 없는 op: " + op;
            }
        }
    } catch (ClassNotFoundException e) {
        error = "com.eactive.ext.djb.DamoManager 클래스를 찾을 수 없습니다. "
              + "damo-manager.jar 를 WAS lib (운영) 또는 WEB-INF/lib 에 배포하세요.";
    } catch (Throwable t) {
        // require-real fail-fast(ExceptionInInitializerError) 또는 초기화 실패(NoClassDefFoundError) 포함
        Throwable c = (t.getCause() != null) ? t.getCause() : t;
        error = c.toString();
        if (c instanceof NoClassDefFoundError
                || error.contains("require-real")
                || error.contains("Could not initialize")) {
            error += "  (※ -Ddamo-manager.require-real=true 인데 scpdb 가 없어 기동에 실패했을 수 있습니다. "
                   + "scpdb 를 갖추거나 옵션을 내리세요.)";
        }
    }

    String badgeColor = "REAL".equals(mode) ? "#1a7f37"
                      : "BYPASS".equals(mode) ? "#9a3412"
                      : "FAKE".equals(mode) ? "#9a6700" : "#6e7781";
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>DamoManager 테스트</title>
<style>
    body   { font-family: -apple-system, "Malgun Gothic", sans-serif; margin: 24px; color: #24292f; }
    h1     { font-size: 20px; margin: 0 0 4px; }
    .sub   { color: #6e7781; font-size: 13px; margin-bottom: 16px; }
    .badge { display:inline-block; color:#fff; padding:2px 10px; border-radius:12px; font-size:12px; font-weight:600; background:<%= badgeColor %>; }
    .meta  { font-size:12px; color:#57606a; margin-left:8px; }
    .card  { border:1px solid #d0d7de; border-radius:8px; padding:16px; max-width:760px; }
    label  { display:block; font-size:13px; font-weight:600; margin:12px 0 4px; }
    textarea, select { width:100%; box-sizing:border-box; font-size:14px; padding:8px; border:1px solid #d0d7de; border-radius:6px; font-family:ui-monospace, Menlo, monospace; }
    textarea { height:90px; resize:vertical; }
    .row    { display:flex; gap:12px; }
    .row > div { flex:1; }
    button  { margin-top:14px; background:#1f6feb; color:#fff; border:0; border-radius:6px; padding:9px 18px; font-size:14px; font-weight:600; cursor:pointer; }
    .result { margin-top:16px; }
    .out    { background:#f6f8fa; border:1px solid #d0d7de; border-radius:6px; padding:12px; white-space:pre-wrap; word-break:break-all; font-family:ui-monospace, Menlo, monospace; font-size:13px; min-height:20px; }
    .err    { color:#cf222e; background:#fff5f5; border-color:#ffc1c1; }
    .hint   { font-size:12px; color:#6e7781; margin-top:18px; line-height:1.6; }
    code    { background:#eff1f3; padding:1px 5px; border-radius:4px; }
</style>
</head>
<body>
    <h1>DamoManager 테스트</h1>
    <div class="sub">웹에서 encrypt / decrypt / hash 동작을 즉시 확인 (eapim-admin)</div>

    <div class="card">
        <div>
            <% if (loaded) { %>
                <span class="badge"><%= mode %> MODE</span>
                <span class="meta">revision=<%= esc(revision) %> · returnCode=<%= esc(returnCode) %></span>
            <% } else { %>
                <span class="badge" style="background:#cf222e;">NOT LOADED</span>
                <span class="meta">damo-manager.jar 미배포</span>
            <% } %>
        </div>

        <form method="post" action="<%= request.getContextPath() %>/damo.jsp">
            <div class="row">
                <div>
                    <label for="op">동작</label>
                    <select id="op" name="op">
                        <option value="encrypt" <%= "encrypt".equals(op) ? "selected" : "" %>>encrypt (암호화)</option>
                        <option value="decrypt" <%= "decrypt".equals(op) ? "selected" : "" %>>decrypt (복호화)</option>
                        <option value="sha256"  <%= "sha256".equals(op)  ? "selected" : "" %>>hash SHA-256</option>
                        <option value="sha512"  <%= "sha512".equals(op)  ? "selected" : "" %>>hash SHA-512</option>
                    </select>
                </div>
            </div>

            <label for="input">입력</label>
            <textarea id="input" name="input" placeholder="암호화/복호화/해시할 문자열"><%= esc(input) %></textarea>

            <input type="hidden" name="run" value="1">
            <button type="submit">실행</button>
        </form>

        <% if (run || error.length() > 0) { %>
        <div class="result">
            <label>결과<% if (run && error.length() == 0) { %> <span class="meta">(<%= esc(op) %>)</span><% } %></label>
            <div class="out <%= error.length() > 0 ? "err" : "" %>"><%= error.length() > 0 ? esc(error) : esc(result) %></div>
        </div>
        <% } %>

        <div class="hint">
            모드 의미 — <b>BYPASS</b>: 무변환 원문 통과(<b>기본값</b>, 옵션 없음) · <b>FAKE</b>: Base64/JRE 해시(<code>-Ddamo-manager.enabled=true</code>, scpdb 없음) · <b>REAL</b>: penta scpdb 실 암복호화(<code>enabled=true</code> + scpdb).<br>
            BYPASS 모드에서는 encrypt/decrypt/hash 모두 입력을 그대로 반환합니다.<br>
            운영은 <code>-Ddamo-manager.require-real=true</code> 로 real 강제(아니면 기동 실패). CLI 로도 동일 확인: <code>java -jar damo-manager.jar enc &lt;text&gt;</code>
        </div>
    </div>
</body>
</html>
