/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004 Bull S.A.
 * Contact: jonas-team@objectweb.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
 *
 * Initial developer: Florent BENOIT
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.objectweb.jonas.ant;

import java.io.File;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.types.Path;

/**
 * Allow to use the BootStrap class <br/>It allows to do some operations like
 * <ul><li>starting/stopping JOnAS</li><li>Deploying some apps</li><li>
 * etc... </li</ul>
 * @author Florent Benoit
 */
public abstract class BootstrapTask extends Task {

    /**
     * Bootstrap class name
     */
    private static final String BOOTSTRAP_CLASS = "org.objectweb.jonas.server.Bootstrap";

    /**
     * Default JOnAS server name
     */
    private static final String DEFAULT_SERVER_NAME = "jonas";

    /**
     * Name of the task (to be displayed in log : default to JOnAS)
     */
    private String taskName = "JOnAS";

    /**
     * JOnAS Root
     */
    private File jonasRoot = null;

    /**
     * Name of the server (default 'jonas')
     */
    private String serverName = DEFAULT_SERVER_NAME;

    /**
     * Name of the server (default 'jonas')
     */
    private String domainName = null;

    /**
     * JOnAS Base
     */
    private File jonasBase = null;

    /**
     * Catalina Home
     */
    private String catalinaHome = null;

    /**
     * Jetty home
     */
    private String jettyHome = null;

    /**
     * Options given to the JVM
     */
    private String jvmOpts = null;

    /**
     * Classpath used for this task
     */
    private Path classpath = null;

    /**
     * Set the JOnAS root directory.
     * @param jonasRoot the JOnAS root directory.
     */
    public void setJonasRoot(File jonasRoot) {
        this.jonasRoot = jonasRoot;
    }

    /**
     * Set the JOnAS base directory.
     * @param jonasBase the JOnAS base directory.
     */
    public void setJonasbase(File jonasBase) {
        this.jonasBase = jonasBase;
    }

    /**
     * Set the additional args to pass to the JVM.
     * @param jvmOpts the options.
     */
    public void setJvmopts(String jvmOpts) {
        this.jvmOpts = jvmOpts;
    }

    /**
     * Adds to the classpath the class of the project
     * @return the path to be configured.
     */
    public Path createClasspath() {
        return new Path(getProject());
    }

    /**
     * Set the classpath for this task
     * @param classpath the classpath to use.
     */
    public void setClasspath(Path classpath) {
        this.classpath = classpath;
    }

    /**
     * Run the task
     * @see org.apache.tools.ant.Task#execute()
     */
    protected Java getBootstraptask(String definedClass) {

        if (jonasRoot == null) {
            // get ant property
            String jr = getProject().getProperty("jonas.root");
            jonasRoot = new File(jr);

            if (jr == null) {
                throw new BuildException("attribute jonasroot is necessary.");
            }
        }

        if (jonasBase == null) {
            jonasBase = jonasRoot;
        }

        Java bootstrapTask = (Java) getProject().createTask("java");
        bootstrapTask.setTaskName(taskName);
        bootstrapTask.setFork(true);
        bootstrapTask.setFailonerror(true);

        // Name of the server
        bootstrapTask.createJvmarg().setValue("-Djonas.name=" + serverName);

        // Name of the domain
        if (domainName != null) {
        	bootstrapTask.createJvmarg().setValue("-Ddomain.name=" + domainName);
        }

        // jonas root
        bootstrapTask.createJvmarg().setValue("-Dinstall.root=" + jonasRoot);

        // jonas base
        bootstrapTask.createJvmarg().setValue("-Djonas.base=" + jonasBase);

        // set headless (for unix without X running)
        bootstrapTask.createJvmarg().setValue("-Djava.awt.headless=true");

        // Properties of JVM
        bootstrapTask.createJvmarg().setValue("-Djonas.default.classloader=true");
        bootstrapTask.createJvmarg().setValue("-Djonas.classpath=");
        bootstrapTask.createJvmarg().setValue(
                "-Djava.naming.factory.initial=org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory");

        // iiop
        bootstrapTask.createJvmarg().setValue("-Dorg.omg.CORBA.ORBClass=org.jacorb.orb.ORB");
        bootstrapTask.createJvmarg().setValue("-Dorg.omg.CORBA.ORBSingletonClass=org.jacorb.orb.ORBSingleton");
        bootstrapTask.createJvmarg().setValue("-Dorg.omg.PortableInterceptor.ORBInitializerClass.standard_init=org.jacorb.orb.standardInterceptors.IORInterceptorInitializer");

        File jonasLibDir = new File(jonasRoot, "lib");
        File jonasLibEndorsedDir = new File(jonasLibDir, "endorsed");
        bootstrapTask.createJvmarg().setValue(
                "-Djavax.rmi.CORBA.PortableRemoteObjectClass=org.objectweb.carol.rmi.multi.MultiPRODelegate");
        bootstrapTask.createJvmarg().setValue(
                "-Djava.naming.factory.initial=org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory");
        bootstrapTask.createJvmarg().setValue("-Djava.endorsed.dirs=" + jonasLibEndorsedDir.getPath());

        // Rmi annotation
        bootstrapTask.createJvmarg().setValue(
                "-Djava.rmi.server.RMIClassLoaderSpi=org.objectweb.jonas.server.RemoteClassLoaderSpi");

        // Webcontainer
        if (catalinaHome != null) {
            bootstrapTask.createJvmarg().setValue("-Dcatalina.home=" + catalinaHome);
        }
        bootstrapTask.createJvmarg().setValue("-Dcatalina.base=" + jonasBase);

        if (jettyHome != null) {
            bootstrapTask.createJvmarg().setValue("-Djetty.home=" + jettyHome);
        }

        // java policy file
        String jonasConfigDir = jonasBase + File.separator + "conf";
        File javaPolicyFile = new File(jonasConfigDir, "java.policy");
        if (javaPolicyFile.exists()) {
            bootstrapTask.createJvmarg().setValue("-Djava.security.policy=" + javaPolicyFile.getPath());
        }
        File javaAuthLoginFile = new File(jonasConfigDir, "jaas.config");
        bootstrapTask.createJvmarg().setValue("-Djava.security.auth.login.config=" + javaAuthLoginFile.getPath());

        // The bootstrap class must launch the defined class
        bootstrapTask.createArg().setValue(definedClass);

        // add jonas_base/conf
        classpath = new Path(getProject(), jonasConfigDir);

        // then add ow_jonas_bootstrap.jar to classloader
        String bootJar = jonasRoot + File.separator + "lib" + File.separator + "common" + File.separator
                + "ow_jonas_bootstrap.jar";
        classpath.append(new Path(getProject(), bootJar));

        // Add tools.jar
        String toolsJar = System.getProperty("java.home") + File.separator + ".." + File.separator + "lib"
                + File.separator + "tools.jar";
        classpath.append(new Path(getProject(), toolsJar));

        // Set the classpath
        bootstrapTask.setClasspath(classpath);

        // class to use = bootstrap class
        bootstrapTask.setClassname(BOOTSTRAP_CLASS);

        // add user defined jvmopts
        if (jvmOpts != null && !jvmOpts.equals("")) {
            bootstrapTask.createJvmarg().setLine(jvmOpts);
        }

        // add jonas name
        if (serverName != null) {
            bootstrapTask.createArg().setValue("-n");
            bootstrapTask.createArg().setValue(getServerName());
        }

        return bootstrapTask;

    }

    /**
     * @return the taskName.
     */
    public String getTaskName() {
        return taskName;
    }

    /**
     * Set the name of the task
     * @param taskName Name of the task
     */
    public void setTaskName(String taskName) {
        this.taskName = taskName;
    }

    /**
     * @return the server Name.
     */
    public String getServerName() {
        return serverName;
    }

    /**
     * Set the name of the server
     * @param serverName The serverName to set.
     */
    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    /**
     * @return the catalinaHome.
     */
    public String getCatalinaHome() {
        return catalinaHome;
    }

    /**
     * Set catalina Home
     * @param catalinaHome The catalinaHome to set.
     */
    public void setCatalinaHome(String catalinaHome) {
        this.catalinaHome = catalinaHome;
    }

    /**
     * @return the jettyHome.
     */
    public String getJettyHome() {
        return jettyHome;
    }

    /**
     * Set jetty home path
     * @param jettyHome The jettyHome to set.
     */
    public void setJettyHome(String jettyHome) {
        this.jettyHome = jettyHome;
    }
    /**
     * @return the jonasRoot.
     */
    public File getJonasRoot() {
        return jonasRoot;
    }

    /**
     * @return the domainName.
     */
    public String getDomainName() {
        return domainName;
    }

    /**
     * Set domainName
     * @param domainName The domainName to set.
     */
    public void setDomainName(String domainName) {
        this.domainName = domainName;
    }

}