<%@ page import="bucket.container.ContainerManager" %>
<%@ page import="com.atlassian.confluence.pages.persistence.dao.AttachmentDao"%>
<%@ page import="java.util.*"%>
<%@ page import="com.atlassian.confluence.pages.Attachment"%>
<%@ page import="com.atlassian.confluence.pages.AttachmentUtils"%>
<%@ page import="java.io.File" %> 

<%@ page contentType="text/html; charset=UTF-8" %>

<html>
    <head>
        <title>Find Missing Attachments</title>
    </head>
    <body>

<%
if (request.getMethod().equals("POST") && request.getParameter("find") != null)
{
	out.print("<div>Beginning search...</div>");

	AttachmentDao attachmentDao = (AttachmentDao) ContainerManager.getComponent("hibernateFileSystemAttachmentDao");
	String attachmentDir = AttachmentUtils.getConfluenceAttachmentDirectory();
	Iterator attachments = attachmentDao.findAll().iterator();
	
	int missingCount = 0;
	
	while (attachments.hasNext())
	{
		Attachment attachment = (Attachment) attachments.next();
		if (!attachment.isLatestVersion())
			continue;
			
		File expectedName = new File(attachmentDir + "/" + attachment.getContent().getId() + "/" + attachment.getId() + "/" + attachment.getVersion());
		
		if (!expectedName.exists()) 
		{
			out.print("<div>Missing attachment: " + expectedName + ", filename: " + attachment.getFileName() + ", filetype: " + attachment.getNiceType() + "</div>");
			++missingCount;
		}
	}
	
	out.print(String.valueOf(missingCount) + " missing attachments");
}
else
{
%>
    <p>This script will report on any missing filesystem attachments</p>
    <form action="" method="post">
        <input type="hidden" name="find" value="yes" />
        <input type="submit" value="Missing attachment report" />
    </form>
<%
}
%>
    </body>
</html>
