/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2007 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library 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 2.1 of the License, or any later version.
 *
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.web.base.lib;

//import java
import java.io.File;
import java.io.IOException;
import java.util.jar.JarFile;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.jonas.lib.util.Log;
import org.ow2.jonas.web.JWebContainerServiceException;
import org.ow2.util.file.FileUtils;
import org.ow2.util.file.FileUtilsException;

/**
 * This class provides an implementation of tools methods than permit to unpack
 * a jar.
 * @author Ludovic Bert
 * @author Florent Benoit
 */
public final class JarTools {

    /**
     * Logger.
     */
    private static Logger logger = Log.getLogger(Log.JONAS_WEB_PREFIX);

    /**
     * No public constructor : utility class.
     */
    private JarTools() {

    }

    /**
     * Unpack the specified jar to the specified directory.
     * @param fileName the name of the archive file to unpack.
     * @param destDir the destination directory of the unpacking.
     * @throws JWebContainerServiceException if an error occurs during the
     *         unpacking.
     */
    public static void unpack(final String fileName,
                              final String destDir) throws JWebContainerServiceException {

        boolean doUnpack = false;

        // Check if the file to unpack exists.
        File jarFile = new File(fileName);
        if (!jarFile.exists()) {
            String err = "Cannot unpack " + fileName + " file does not exist";
            throw new JWebContainerServiceException(err);
        }

        // Check if the destination dir exists.
        File dest = new File(destDir);
        if (dest.exists()) {
            // Check if the destination directory is up to date and unpack it
            // if necessary.
            if (dest.lastModified() < jarFile.lastModified()) {
                if (removeDirectory(dest)) {
                    doUnpack = true;
                } else {
                    String err = "Cannot unpack " + fileName;
                    err = err + " cannot delete existing unpacked directory";
                    new JWebContainerServiceException(err);
                }
            } // else nothing to do the dest dir is up to date.
        } else {
            doUnpack = true;
        }

        // Unpack if necessary
        if (doUnpack) {
            JarFile packedJar = null;
            try {
                packedJar = new JarFile(fileName);
                // redirect to FileUtils
                FileUtils.unpack(packedJar, dest);
            } catch (IOException e) {
                String err = "Error while trying to create JarFile object on '" + fileName + "'";
                throw new JWebContainerServiceException(err, e);
            } catch (FileUtilsException e) {
                String err = "Error while unpacking jar '" + fileName + "'";
                throw new JWebContainerServiceException(err, e);
            } finally {
                try {
                    if (packedJar != null) {
                        packedJar.close();
                    }
                } catch (IOException ioe) {
                    if (logger.isLoggable(BasicLevel.DEBUG)) {
                        logger.log(BasicLevel.DEBUG, "Cannot close jarfile '" + packedJar + "'.");
                    }
                }
            }
        }
    }



    /**
     * Remove a directory with all its child (recursive remove).
     * @param file the name of the file or directory to remove.
     * @return true if only if the directory is removed.
     */
    private static boolean removeDirectory(final File file) {
        boolean removeOk = true;

        //File or directory doesn't exists, exit.
        if (!file.exists()) {
            return false;
        }

        //Remove the child before the current file(directory)
        if (file.isDirectory()) {
            //remove all the children
            File[] childFiles = file.listFiles();
            for (int i = 0; i < childFiles.length; i++) {
                removeOk = removeOk && removeDirectory(childFiles[i]);
            }
        }
        //Since all childs are removed , remove us
        removeOk = removeOk && file.delete();
        return removeOk;
    }
}
