<%@ page import="com.atlassian.confluence.security.SpacePermission" %>
<%@ page import="com.atlassian.confluence.security.SpacePermissionCaseFixer" %>
<%@ page import="com.atlassian.confluence.security.SpacePermissionManager" %>
<%@ page import="com.atlassian.confluence.security.persistence.dao.SpacePermissionDao" %>
<%@ page import="com.atlassian.confluence.spaces.Space" %>
<%@ page import="com.atlassian.confluence.spaces.SpaceManager" %>
<%@ page import="com.atlassian.confluence.user.UserAccessor" %>
<%@ page import="com.atlassian.spring.container.ContainerManager" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%

    String doFix = request.getParameter("doFix");

    if (doFix != null)
    {
        out.println("<p>Starting space permissions fix ...</p>");

        UserAccessor userAccessor = (UserAccessor) ContainerManager.getComponent("userAccessor");
        SpacePermissionManager spacePermissionManager = (SpacePermissionManager) ContainerManager.getComponent("spacePermissionManager");
        SpacePermissionDao spacePermissionDao = (SpacePermissionDao) ContainerManager.getComponent("spacePermissionDao");
        SpaceManager spaceManager = (SpaceManager) ContainerManager.getComponent("spaceManager");
        SpacePermissionCaseFixer caseFixer = new SpacePermissionCaseFixer(userAccessor, spacePermissionManager, out);

        // fix space permissions
        List spaces = spaceManager.getAllSpaces();
        for (Iterator spacesIterator = spaces.iterator(); spacesIterator.hasNext();)
        {
            Space space = (Space) spacesIterator.next();
            List spacePermissions = spacePermissionDao.findPermissionsForSpace(space);
            for (Iterator permissionsIterator = spacePermissions.iterator(); permissionsIterator.hasNext();)
            {
                SpacePermission spacePermission = (SpacePermission) permissionsIterator.next();
                caseFixer.fix(spacePermission);
            }
        }

        // fix global permissions
        List globalPermissions = spacePermissionManager.getGlobalPermissions();
        for (Iterator globaPermsIterator = globalPermissions.iterator(); globaPermsIterator.hasNext();)
        {
            SpacePermission spacePermission = (SpacePermission) globaPermsIterator.next();
            caseFixer.fix(spacePermission);
        }

        out.println("<p>Space permissions fix complete.</p>");
    }
    else
    {
%>

<form action="fixCaseInSpacePermissions.jsp" id="fixCaseInSpacePermissions" method="post">
    This JSP will fix the case of your space permissions. Do you wish to proceed?
    <p/>
    <input type="hidden" name="doFix" value="true"/>
    <input type="submit" value="Proceed"/>
</form>

<%
    }

%>