/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008
 * 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.services.bootstrap;

import java.io.File;
import java.io.FilenameFilter;
import java.util.List;

import org.ow2.jonas.configuration.ConfigurationManager;
import org.ow2.jonas.configuration.ServiceDeployer;
import org.ow2.jonas.lib.bootstrap.JProp;
import org.ow2.jonas.properties.ServerProperties;
import org.ow2.util.archive.api.IArchive;
import org.ow2.util.archive.impl.ArchiveManager;
import org.ow2.util.ee.deploy.api.deployable.IDeployable;
import org.ow2.util.ee.deploy.api.deployer.IDeployerManager;
import org.ow2.util.ee.deploy.impl.helper.DeployableHelper;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * Allows to deploy or undeploy all bundles for a particular service. At the
 * server initialization, deploy all JOnAS services defined in the
 * configuration.
 * @author Francois Fornaciari
 */
public class JOnASServiceDeployer extends Thread implements ServiceDeployer {

    /**
     * {@ConfigurationManager} reference.
     */
    private ConfigurationManager configurationManager = null;

    /**
     * DeployerManager reference.
     */
    private IDeployerManager deployerManager = null;

    /**
     * ServerProperties service object.
     */
    private ServerProperties serverProperties = null;

    /**
     * Logger.
     */
    private Log logger = LogFactory.getLog(JOnASServiceDeployer.class);

    /**
     * Property name for the bootstrap mode.
     */
    private static final String JONAS_BOOTSTRAP = "jonas.bootstrap";

    /**
     * Property name for the service name.
     */
    private static final String JONAS_SERVICE = "jonas.service";

    /**
     * JOnAS configuration directory.
     */
    private static final String DEPLOYMENT_CONFIG_DIR = JProp.getConfDir() + File.separator + "deployment";

    /**
     * Deploy all JOnAS services defined in the configuration.
     */
    public void init() {
        new Thread(this).start();
    }

    @Override
    public void run() {
        boolean boostrapMode = Boolean.getBoolean(JONAS_BOOTSTRAP);

        if (!boostrapMode) {
            List<String> services = configurationManager.getOptionalServices();
            for (String service : services) {
                deployService(service);
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public void deployService(final String serviceName) {
        logger.debug("Deploying the service ''{0}''", serviceName);

        String service = serviceName;
        File configDir = new File(DEPLOYMENT_CONFIG_DIR);

        try {
            final String baseName = serviceName + "-base";
            File[] base = configDir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return (name.equalsIgnoreCase(baseName.concat(".xml")));
                }
            });
            if (base.length == 1) {
                deployService(baseName);

                // Get the name of the user-defined implementation service
                String serviceClass = serverProperties.getValue(JONAS_SERVICE + "." + service + ".class");
                // The value follows this construction:
                // org.ow2.jonas.<service>.<implementation>.<...>
                // The implementation name is the 5th element.
                // TODO: method not easily extensible if the package name doesn't start with org.ow2.jonas
                String implementationName = serviceClass.split("\\.")[4];

                // Deploy the <service>-<implementationName>.xml file
                service += "-" + implementationName;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        File file = new File(DEPLOYMENT_CONFIG_DIR, service + ".xml");
        if (file.exists()) {
            deployPlan(file);
        } else {
            logger.error("Cannot deploy the service ''{0}'', file ''{1}'' not found", service, file);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void undeployService(final String serviceName) {
        logger.debug("Undeploying the service ''{0}''", serviceName);

        File file = new File(DEPLOYMENT_CONFIG_DIR, serviceName + ".xml");
        if (file.exists()) {
            undeployPlan(file);
        } else {
            logger.error("Cannot undeploy the service ''{0}'', file ''{1}'' not found", serviceName, file);
        }
    }

    /**
     * Deploy a service using its associated deployment plan file.
     * @param file File corresponding to the plan to deploy
     */
    private void deployPlan(final File file) {
        logger.debug("Deploying the deployment plan for ''{0}''", file);

        // Get the deployable
        IArchive archive = ArchiveManager.getInstance().getArchive(file);
        if (archive == null) {
            logger.warn("Ignoring invalid file ''{0}''", file);
            return;
        }

        IDeployable<?> deployable = null;
        try {
            deployable = DeployableHelper.getDeployable(archive);
            deployerManager.deploy(deployable);
        } catch (Exception e) {
            logger.error("Cannot get a deployable for the archive ''{0}''", archive, e);
        }
    }

    /**
     * Undeploy a service using its associated deployment plan file.
     * @param file File corresponding to the plan to undeploy
     */
    private void undeployPlan(final File file) {
        logger.debug("Undeploying the deployment plan for ''{0}''", file);

        // Get the deployable
        IArchive archive = ArchiveManager.getInstance().getArchive(file);
        if (archive == null) {
            logger.warn("Ignoring invalid file ''{0}''", file);
            return;
        }

        IDeployable<?> deployable = null;
        try {
            deployable = DeployableHelper.getDeployable(archive);
            deployerManager.undeploy(deployable);
        } catch (Exception e) {
            logger.error("Cannot undeploy the deployment plan for ''{0}''", file, e);
        }
    }

    /**
     * @param configurationManager the configurationManager to set
     */
    public void setConfigurationManager(final ConfigurationManager configurationManager) {
        this.configurationManager = configurationManager;
    }

    /**
     * @param deployerManager the deployerManager to set
     */
    public void setDeployerManager(final IDeployerManager deployerManager) {
        this.deployerManager = deployerManager;
    }

    /**
     * Set the server properties service.
     * @param serverProperties the serverProperties to set
     */
    public void setServerProperties(final ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }
}
