/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2005 Robert Harder - rob@iharder.net
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.buildtools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;

/**
 *
 * @author chm
 */
public class LgplConverter {
    private String srcDir, targetDir;
    private FileFilter filter;
    private boolean succeded;
    private static String CRLF = System.getProperty("line.separator");
    
    public LgplConverter(final String srcDir, final String targetDir) {
        super();
        this.srcDir=srcDir;
        this.targetDir=targetDir;
        filter = new MyFilter();
    }
    
    public void run() {
        succeded = true;
        copyFilesFilter(srcDir,targetDir);
        if(!succeded) System.exit(1);
        System.exit(0);
    }
    
    private void copyFilesFilter(final String src, final String target) {
        File fSrc = new File(src);
        File fTarget = new File(target);
        
        if(!fTarget.exists()) fTarget.mkdirs();
        File[] files = fSrc.listFiles(filter);
        for(File f: files) {
            if(f.isDirectory()) {
                if(!f.getName().equals("CVS"))
                    copyFilesFilter(f.getAbsolutePath(),new File(fTarget,f.getName()).getAbsolutePath());
            } else {
                if(f.getName().endsWith(".java")) {
                    try {
                        BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(f),"ISO-8859-1"));
                        PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(fTarget,f.getName())),"ISO-8859-1"));
                        StringBuffer entete = new StringBuffer();
                        String line;
                        boolean packageReached = false;
                        do {
                            line = rdr.readLine();
                            if(line!=null) {
                                if(!packageReached) {
                                    if(line.trim().startsWith("package ")) {
                                        packageReached = true;
                                    } else {
                                        entete.append(line).append(CRLF);
                                    }
                                    if(packageReached) {
                                        if(entete.length()<10) {
                                            System.err.println(f.getAbsolutePath()+" has no license header");
                                        }
                                        String s = convertEntete(entete.toString());
                                        pw.println(s);
                                        pw.println(line);
                                    }
                                } else {
                                    pw.println(line);
                                }
                            }
                        } while(line!=null);
                        pw.flush(); pw.close(); rdr.close();
                    } catch(IOException ioEx) {
                        ioEx.printStackTrace(System.err);
                        succeded=false;
                        System.exit(1);
                    }
                } else {
                    try {
                        FileChannel fChIn = new FileInputStream(f).getChannel();
                        FileChannel fChOut = new FileOutputStream(new File(fTarget,f.getName())).getChannel();
                        fChIn.transferTo(0, fChIn.size(), fChOut);
                        fChIn.close(); fChOut.close();
                    } catch(Exception ex) {}
                }
            }
        }
    }
    
    protected String convertEntete(String entete) {
        if(isLicenseGPL(entete)) {
            StringBuffer out = new StringBuffer();
            out.append("/*").append(CRLF).append(" * Copyright").append(CRLF);
            out.append(" *   2007 axYus - www.axyus.com").append(CRLF);
            // ajout des auteurs
            BufferedReader br = new BufferedReader(new StringReader(entete));
            String s = null;
            do {
                try {
                    s = br.readLine();
                    if(s!=null) {
                        if(s.matches("^ \\*  +[0-9]{4} [^a][^x][^Y][^u][^s].*$")) {
                            out.append(s).append(CRLF);
                        }
                    }
                } catch(IOException ioEx) { ioEx.printStackTrace(); }
            } while(s!=null);
            //
            out.append(" *").append(CRLF);
            out.append(" * This file is part of XEMELIOS.").append(CRLF);
            out.append(" *").append(CRLF);
            out.append(" * XEMELIOS is free software; you can redistribute it and/or modify").append(CRLF);
            out.append(" * it under the terms of the GNU Lesser General Public License as published by").append(CRLF);
            out.append(" * the Free Software Foundation; either version 3 of the License, or").append(CRLF);
            out.append(" * (at your option) any later version.").append(CRLF);
            out.append(" *").append(CRLF);
            out.append(" * XEMELIOS is distributed in the hope that it will be useful,").append(CRLF);
            out.append(" * but WITHOUT ANY WARRANTY; without even the implied warranty of").append(CRLF);
            out.append(" * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the").append(CRLF);
            out.append(" * GNU Lesser General Public License for more details.").append(CRLF);
            out.append(" *").append(CRLF);
            out.append(" * You should have received a copy of the GNU Lesser General Public License").append(CRLF);
            out.append(" * along with XEMELIOS; if not, write to the Free Software").append(CRLF);
            out.append(" * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA").append(CRLF);
            out.append(" */").append(CRLF);
            return out.toString();
        } else return entete;
    }
    protected boolean isLicenseGPL(String s) {
        return s.contains("XEMELIOS is free software; you can redistribute it and/or modify") && s.contains("it under the terms of the GNU General Public License as published by");
    }
    
    public static void main(String args[]) {
        if(args.length==2) {
            File fIn = new File(args[0]);
            File fOut = new File(args[1]);
            new LgplConverter(fIn.getAbsolutePath(),fOut.getAbsolutePath()).run();
        }
        
    }

    private class MyFilter implements FileFilter {

        public boolean accept(File pathname) {
            return pathname.isDirectory() || pathname.getName().endsWith(".java");
        }
        
        
    }
}
