package railo.commons.io;

import java.io.IOException;
import java.io.InputStream;

import railo.commons.io.res.Resource;
import railo.commons.lang.StringUtil;

public class FileRotation {
	public static void checkFile(Resource res, long maxFileSize, int maxFiles, byte[] header) throws IOException {
        boolean writeHeader=false;
        // create file
        if(!res.exists()) {
            res.createFile(true);
            writeHeader=true;
        }
        else if(res.length()==0) {
            writeHeader=true;
        }
        
        
        // create new file
        else if(res.length()>maxFileSize) {
            Resource parent = res.getParentResource();
            String name = res.getName();
            int lenMaxFileSize=(""+maxFiles).length();       
            for(int i=maxFiles;i>0;i--) {
            	
                Resource to=parent.getRealResource(name+"."+StringUtil.addZeros(i, lenMaxFileSize)+".bak");
                Resource from=parent.getRealResource(name+"."+StringUtil.addZeros(i-1,lenMaxFileSize)+".bak");
                if(from.exists()) {
                    if(to.exists())to.delete();
                    from.renameTo(to);
                }
            }
            res.renameTo(parent.getRealResource(name+"."+StringUtil.addZeros(1,lenMaxFileSize)+".bak"));
            res=parent.getRealResource(name);//new File(parent,name);
            res.createNewFile();
            writeHeader=true;
        }
        else {
        	byte[] buffer = new byte[header.length];
            int len;
            InputStream in = null;
            try{
	            in = res.getInputStream();
	            boolean headerOK = true;
	            len = in.read(buffer);
	        	if(len==header.length){
	        		for(int i=0;i<header.length;i++) {
	        			if(header[i]!=buffer[i]){
	        				headerOK=false;
	        				break;
	        			}
	        		}
	        	}
	        	else headerOK=false;
	            if(!headerOK)writeHeader=true;
            }
            finally {
            	IOUtil.closeEL(in);
            }
        }
        
        
        if(writeHeader) {
            IOUtil.write(res, header,false);
        }   
    }
}

@@ -1466,16 +1466,52 @@
     else
+ if(header!=null && header.length%3E0)
  %7B%0A     
@@ -2156,24 +2156,72 @@
 teHeader) %7B%0A
+            if(header==null)header=new byte%5B0%5D;%0A
             
@@ -2249,24 +2249,36 @@
 der,false);%0A
+           %0A
         %7D   

add helper class for file rotation