<%@ page import="org.jivesoftware.util.LocaleUtils"%>
<%@ page import="org.jivesoftware.util.ParamUtils"%>
<%@ page import="java.util.*" %>
<%@ page import="org.jivesoftware.openfire.clearspace.ClearspaceManager" %>
<%@ page import="org.jivesoftware.util.JiveGlobals" %>
<%@ page import="org.jivesoftware.util.StringUtils" %>

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<%
    String uri;
    String sharedSecret;
    String existingHashSharedSecret = "";
    String plainSharedSecret = null;

    boolean verifyChain = JiveGlobals.getBooleanProperty("clearspace.certificate.verify.chain", true);
    boolean verifyRoot = JiveGlobals.getBooleanProperty("clearspace.certificate.verify.root", true);
    boolean selfSigned = JiveGlobals.getBooleanProperty("clearspace.certificate.accept-selfsigned", false);
    boolean verifyIdentity = JiveGlobals.getBooleanProperty("clearspace.certificate.verify.identity", false);
    boolean verifyValidity = JiveGlobals.getBooleanProperty("clearspace.certificate.verify.validity", true);


    // Get parameters
    boolean save = request.getParameter("save") != null;
    boolean test = request.getParameter("test") != null;
    @SuppressWarnings("unchecked")
    Map<String,String> xmppSettings = (Map<String,String>)session.getAttribute("xmppSettings");

    ClearspaceManager manager;
    if (ClearspaceManager.getInstance() != null) {
        // Use the existing manager. This will be the case after setup was completed
        manager = ClearspaceManager.getInstance();
    }
    else {
        manager = new ClearspaceManager();
    }
    Map<String, String> errors = new HashMap<String, String>();

    // If we came from a prelogin error, show it and remove it from the session
    String preloginError = (String) session.getAttribute("prelogin.setup.error");
    if (preloginError != null) {
        errors.put("prelogin", LocaleUtils.getLocalizedString(preloginError));
        session.removeAttribute("prelogin.setup.error");
    }

    if (save || test) {
        uri = ParamUtils.getParameter(request, "uri");
        if (uri == null) {
            errors.put("uri", LocaleUtils.getLocalizedString("setup.clearspace.service.uri_error"));
        }
        // this could be the new entered plain shared secret or the current hashed shared secret
        sharedSecret = ParamUtils.getParameter(request, "sharedSecret");

        // this will store new entered plain shared secret or the current plain shared secret
        //String plainSharedSecret = null;
        if (sharedSecret == null || sharedSecret.length() == 0) {
            errors.put("secret", LocaleUtils.getLocalizedString("setup.clearspace.service.secret_error"));
        } else {
            // set to the current plain shared secret
            plainSharedSecret = manager.getSharedSecret();

            // Hash the current shared secret
            if (plainSharedSecret != null) {
                existingHashSharedSecret = StringUtils.hash(plainSharedSecret);
            }
            // Check if the new shared secret was changed. If it wasn't changed, then it is the original hashed shared secret
            // NOTE: if the new PLAIN password equals the previous HASHED password this fails, but is unlikely.
            if (!existingHashSharedSecret.equals(sharedSecret)) {
                // Hash the new shared secret since it was changed
                String newHashSharedSecret = "";
                if (sharedSecret != null) {
                        newHashSharedSecret = StringUtils.hash(sharedSecret);
                }

                // Change password if their hash values are different
                if (!existingHashSharedSecret.equals(newHashSharedSecret)) {
                    plainSharedSecret = sharedSecret;
                }
            }
        }

        verifyChain = ParamUtils.getBooleanParameter(request, "verifyChain", verifyChain);
        verifyRoot = ParamUtils.getBooleanParameter(request, "verifyRoot", verifyRoot);
        selfSigned = ParamUtils.getBooleanParameter(request, "selfSigned", selfSigned);
        verifyIdentity = ParamUtils.getBooleanParameter(request, "verifyIdentity", verifyIdentity);
        verifyValidity = ParamUtils.getBooleanParameter(request, "verifyValidity", verifyValidity);

        Map<String, String> settings = new HashMap<String, String>();
        // If there are no errors check if there is a need to run a force test
        if (errors.isEmpty()) {
            // Store settings in a map and keep it in the session
            settings.put("clearspace.uri", uri);

            // Sets the current shared secret, it will be changed if the new shared secret is different
            settings.put("clearspace.sharedSecret", plainSharedSecret);

            settings.put("clearspace.certificate.verify.chain", Boolean.toString(verifyChain));
            settings.put("clearspace.certificate.verify.root", Boolean.toString(verifyRoot));
            settings.put("clearspace.certificate.accept-selfsigned", Boolean.toString(selfSigned));
            settings.put("clearspace.certificate.verify.identity", Boolean.toString(verifyIdentity));
            settings.put("clearspace.certificate.verify.validity", Boolean.toString(verifyValidity));

            if (save && forceTest) {
                ClearspaceManager managerTest = new ClearspaceManager(settings);
                if (managerTest.testConnection() != null) {
                    // if there is any problems don't save it
                    // add an error (this is the reason of why this check is in another "if errors.isEmpty()"
                    errors.put("connection", LocaleUtils.getLocalizedString("setup.clearspace.service.connection_error"));
                }
            }
        }

        if (errors.isEmpty()) {
            session.setAttribute("clearspaceSettings", settings);

            if (save) {

                // Save settings and redirect
                manager.setConnectionURI(uri);
                manager.setSharedSecret(plainSharedSecret);

                // Enable the Clearspace auth, user, group, vcard, lockout, security audit, and admin providers.
                JiveGlobals.setProperty("provider.auth.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceAuthProvider");
                JiveGlobals.setProperty("provider.user.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceUserProvider");
                JiveGlobals.setProperty("provider.group.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceGroupProvider");
                JiveGlobals.setProperty("provider.vcard.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceVCardProvider");
                JiveGlobals.setProperty("provider.lockout.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceLockOutProvider");
                JiveGlobals.setProperty("provider.securityAudit.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceSecurityAuditProvider");
                JiveGlobals.setProperty("provider.admin.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceAdminProvider");

                // Set configuration for certificate validation
                JiveGlobals.setProperty("clearspace.certificate.verify.chain", Boolean.toString(verifyChain));
                JiveGlobals.setProperty("clearspace.certificate.verify.root", Boolean.toString(verifyRoot));
                JiveGlobals.setProperty("clearspace.certificate.accept-selfsigned", Boolean.toString(selfSigned));
                JiveGlobals.setProperty("clearspace.certificate.verify.identity", Boolean.toString(verifyIdentity));
                JiveGlobals.setProperty("clearspace.certificate.verify.validity", Boolean.toString(verifyValidity));

                // Save the settings for later, if we're in setup
                if (xmppSettings != null) {
                    xmppSettings.put("provider.auth.className",
                            "org.jivesoftware.openfire.clearspace.ClearspaceAuthProvider");
                    xmppSettings.put("provider.user.className",
                            "org.jivesoftware.openfire.clearspace.ClearspaceUserProvider");
                    xmppSettings.put("provider.group.className",
                            "org.jivesoftware.openfire.clearspace.ClearspaceGroupProvider");
                    xmppSettings.put("provider.vcard.className",
                            "org.jivesoftware.openfire.clearspace.ClearspaceVCardProvider");
                    xmppSettings.put("provider.lockout.className",
                            "org.jivesoftware.openfire.clearspace.ClearspaceLockOutProvider");
                    xmppSettings.put("provider.securityAudit.className",
                            "org.jivesoftware.openfire.clearspace.ClearspaceSecurityAuditProvider");
                    xmppSettings.put("provider.admin.className",
                            "org.jivesoftware.openfire.clearspace.ClearspaceAdminProvider");
                    xmppSettings.put("clearspace.uri", uri);
                    xmppSettings.put("clearspace.sharedSecret", plainSharedSecret);
                    xmppSettings.put("clearspace.certificate.verify.chain", Boolean.toString(verifyChain));
                    xmppSettings.put("clearspace.certificate.verify.root", Boolean.toString(verifyRoot));
                    xmppSettings.put("clearspace.certificate.accept-selfsigned", Boolean.toString(selfSigned));
                    xmppSettings.put("clearspace.certificate.verify.identity", Boolean.toString(verifyIdentity));
                    xmppSettings.put("clearspace.certificate.verify.validity", Boolean.toString(verifyValidity));
                    session.setAttribute("xmppSettings", xmppSettings);
                }
                if (initialSetup) {
                    // Set that the setup has been completed
                    JiveGlobals.setXMLProperty("setup","true");
                }
                // Redirect to next step.
                response.sendRedirect(nextPage);
                return;
            }
        }
    } else {
        // See if there are already values for the variables defined.
        uri = manager.getConnectionURI();
        sharedSecret = manager.getSharedSecret() == null || manager.getSharedSecret().trim().length() == 0 ? "" : StringUtils.hash(manager.getSharedSecret());
    }
%>
<html>
<head>
    <title><fmt:message key="setup.clearspace.title" /></title>
    <% for (Map.Entry<String, String> entry : meta.entrySet()) { %>
    <meta name="<%= entry.getKey()%>" content="<%= entry.getValue()%>"/>
    <% } %>
</head>
<body>
    <% if (test && errors.isEmpty()) { %>

        <a href="<%= testPage%>" id="lbmessage" title="<fmt:message key="global.test" />" style="display:none;"></a>
        <script type="text/javascript">
            function loadMsg() {
                var lb = new lightbox(document.getElementById('lbmessage'));
                lb.activate();
            }
            setTimeout('loadMsg()', 250);
        </script>

    <% } %>

    <% if (initialSetup) { %>
    <h1><fmt:message key="setup.clearspace.profile" />: <span><fmt:message key="setup.clearspace.service.integration" /></span></h1>
    <% } %>

    <div id="jive-contentBox_stepbar">
        <span class="jive-stepbar_step"><strong><fmt:message key="setup.clearspace.service.connection_settings" /></strong></span>
    </div>

    <div class="jive-contentBox jive-contentBox_for-stepbar">
    <h2><span><fmt:message key="setup.clearspace.service.connection_settings" /></span></h2>

    <p><fmt:message key="setup.clearspace.service.description" /></p>

    <%  if (errors.size() > 0) { %>

    <div class="error">
        <% for (String error:errors.values()) { %>
            <%= error%><br/>
        <% } %>
    </div>

    <%  } %>

    <form action="<%= currentPage%>" method="post">
		<!-- BEGIN jive-contentBox_bluebox -->
		<div class="jive-contentBox_bluebox">
			<table border="0" cellpadding="0" cellspacing="2" width="100%">
			<tr>
			    <td colspan="4"><strong><fmt:message key="setup.clearspace.service" /></strong></td>
			</tr>
            <tr>
			    <td align="right" width="1%" nowrap="nowrap"><fmt:message key="setup.clearspace.service.uri" />:</td>
                <td width="1%">
                    <table cellpadding="0" cellspacing="0" border="0" width="100%">
                    <tr>
                        <td width="1%" nowrap="nowrap">
                            <input type="text" name="uri" id="jiveCLEARSPACEuri" size="40" maxlength="255" value="<%= uri!=null?uri:"" %>">
                        </td>
                        <td width="99%">
                            <span class="jive-setup-helpicon" onmouseover="domTT_activate(this, event, 'content', '<fmt:message key="setup.clearspace.service.uri_help" />', 'styleClass', 'jiveTooltip', 'trail', true, 'delay', 300, 'lifetime', 8000);"></span>
                        </td>
                    </tr>
                    </table>
                </td>
			</tr>
			<tr>
                <td align="right" width="1%" nowrap="nowrap"><fmt:message key="setup.clearspace.service.secret" /> <%=plainSharedSecret%>:</td>
                <td colspan="3">
                    <table cellpadding="0" cellspacing="0" border="0" width="100%">
                    <tr>
                        <td width="1%" nowrap="nowrap">
                            <input type="password" name="sharedSecret" id="jiveCLEARSPACEsecret" size="22" maxlength="35" value="<%= (sharedSecret != null) ? sharedSecret : "" %>">
                        </td>
                        <td width="99%">
                            <span class="jive-setup-helpicon" onmouseover="domTT_activate(this, event, 'content', '<fmt:message key="setup.clearspace.service.secret_help" />', 'styleClass', 'jiveTooltip', 'trail', true, 'delay', 300, 'lifetime', -1);"></span>
                        </td>
                    </tr>
                    </table>
                </td>
			</tr>
			</table>
        </div>
		<!-- END jive-contentBox_bluebox -->

        <!-- BEGIN jiveAdvancedButton -->
        <div class="jiveAdvancedButton">
            <a href="#" onclick="togglePanel(jiveAdvanced); return false;" id="jiveAdvancedLink"><fmt:message key="setup.clearspace.service.advanced" /></a>
        </div>
        <!-- END jiveAdvancedButton -->

        <!-- BEGIN jiveAdvancedPanelcs (advanced connection settings) -->
        <div class="jiveadvancedPanelcs" id="jiveAdvanced" style="display: none;">
            <div>
                <table border="0" cellpadding="0" cellspacing="1">
                <thead>
                <tr>
                    <th width="10%"></th>
                    <th></th>
                    <th width="50"><fmt:message key="global.yes" /></th>
                    <th width="50"><fmt:message key="global.no" /></th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td class="jive-advancedLabel" nowrap>
                        <fmt:message key="setup.clearspace.service.certificate.verify.chain" />:
                    </td>
                    <td class="jive-advancedDesc jive-advancedBorderBottom jive-advancedBorderRight">
                        <fmt:message key="setup.clearspace.service.certificate.verify.chain_help" />
                    </td>
                    <td class="jive-advancedBorderBottom jive-advancedBorderRight" align="center">
                        <input type="radio" name="verifyChain" value="true" <% if (verifyChain) { %>checked <% } %>>
                    </td>
                    <td class="jive-advancedBorderBottom" align="center">
                        <input type="radio" name="verifyChain" value="false" <% if (!verifyChain) { %>checked <% } %>>
                    </td>
                </tr>
                <tr>
                    <td class="jive-advancedLabel" nowrap>
                        <fmt:message key="setup.clearspace.service.certificate.verify.root" />:
                    </td>
                    <td class="jive-advancedDesc jive-advancedBorderBottom jive-advancedBorderRight">
                        <fmt:message key="setup.clearspace.service.certificate.verify.root_help" />
                    </td>
                    <td class="jive-advancedBorderBottom jive-advancedBorderRight" align="center">
                        <input type="radio" name="verifyRoot" value="true" <% if (verifyRoot) { %>checked <% } %>>
                    </td>
                    <td class="jive-advancedBorderBottom" align="center">
                        <input type="radio" name="verifyRoot" value="false" <% if (!verifyRoot) { %>checked <% } %>>
                    </td>
                </tr>
                <tr>
                    <td class="jive-advancedLabel" nowrap>
                        <fmt:message key="setup.clearspace.service.certificate.accept-selfsigned" />:
                    </td>
                    <td class="jive-advancedDesc jive-advancedBorderBottom jive-advancedBorderRight">
                        <fmt:message key="setup.clearspace.service.certificate.accept-selfsigned_help" />
                    </td>
                    <td class="jive-advancedBorderBottom jive-advancedBorderRight" align="center">
                        <input type="radio" name="selfSigned" value="true" <% if (selfSigned) { %>checked <% } %>>
                    </td>
                    <td class="jive-advancedBorderBottom" align="center">
                        <input type="radio" name="selfSigned" value="false" <% if (!selfSigned) { %>checked <% } %>>
                    </td>
                </tr>
                <tr>
                    <td class="jive-advancedLabel" nowrap>
                        <fmt:message key="setup.clearspace.service.certificate.verify.identity" />:
                    </td>
                    <td class="jive-advancedDesc jive-advancedBorderBottom jive-advancedBorderRight">
                        <fmt:message key="setup.clearspace.service.certificate.verify.identity_help" />
                    </td>
                    <td class="jive-advancedBorderBottom jive-advancedBorderRight" align="center">
                        <input type="radio" name="verifyIdentity" value="true" <% if (verifyIdentity) { %>checked <% } %>>
                    </td>
                    <td class="jive-advancedBorderBottom" align="center">
                        <input type="radio" name="verifyIdentity" value="false" <% if (!verifyIdentity) { %>checked <% } %>>
                    </td>
                </tr>
                <tr>
                    <td class="jive-advancedLabel" nowrap>
                        <fmt:message key="setup.clearspace.service.certificate.verify.validity" />:
                    </td>
                    <td class="jive-advancedDesc jive-advancedBorderBottom jive-advancedBorderRight">
                        <fmt:message key="setup.clearspace.service.certificate.verify.validity_help" />
                    </td>
                    <td class="jive-advancedBorderBottom jive-advancedBorderRight" align="center">
                        <input type="radio" name="verifyValidity" value="true" <% if (verifyValidity) { %>checked <% } %>>
                    </td>
                    <td class="jive-advancedBorderBottom" align="center">
                        <input type="radio" name="verifyValidity" value="false" <% if (!verifyValidity) { %>checked <% } %>>
                    </td>
                </tr>
                </tbody>
                </table>
            </div>
        </div>
        <!-- END jiveAdvancedPanelcs (advanced connection settings) -->

        <!-- BEGIN jive-buttons -->
		<div class="jive-buttons">

			<!-- BEGIN right-aligned buttons -->
			<div align="right">

                <input type="Submit" name="test" value="<fmt:message key="setup.clearspace.test" />" id="jive-setup-test" border="0">

                <input type="Submit" name="save" value="<fmt:message key="setup.clearspace.continue" />" id="jive-setup-save" border="0">
			</div>
			<!-- END right-aligned buttons -->

		</div>
		<!-- END jive-buttons -->

	</form>
    </div>
    <!-- END jive-contentBox -->

</body>
</html>
