/** BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2001 Sun Microsystems, Inc.  Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License.
 * 
 * This program 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * END COPYRIGHT BLOCK **/
package com.netscape.management.admserv;

import java.net.URL;
import java.net.MalformedURLException;
import com.netscape.management.nmclf.*;
import com.netscape.management.client.console.ConsoleInfo;
import com.netscape.management.client.topology.IProductObject;
import com.netscape.management.client.util.Debug;
import com.netscape.management.client.util.AdmTask;
import com.netscape.management.client.util.URLByteEncoder;
import com.netscape.management.client.util.ResourceSet;


/**
 * Netscape admin server migration entry point. The directory server
 * needs to contain the name of this class in order for the topology
 * view to load this class for migrating the admin server.
 *
 * @author   phlee
 * @date     01/09/98
 */

public class AdminServerProduct implements IProductObject {

    protected ConsoleInfo _consoleInfo; // global information
    //protected KeyCertMigrationDialog _keyCert;


    /**
     * constructor.
     */
    public AdminServerProduct() {
    }


    /*public static void main(String args[]) {
     AdminServerProduct asp = new AdminServerProduct();
         ConsoleInfo consoleInfo = null;
         try {
             LDAPConnection connection = new LDAPConnection();
             connection.connect("awing", 3000, "uid=admin, ou=Administrators, ou=TopologyManagement, o=NetscapeRoot", "admin");
             consoleInfo = new ConsoleInfo("buddha.mcom.com", 8081, "admin", "admin", "ou=mcom.com, o=NetscapeRoot");
             consoleInfo.setAdminURL("http://buddha.mcom.com:8081/");
             consoleInfo.setBaseDN("cn=admin-serv-buddha, ou=mcom.com, o=NetscapeRoot");
             consoleInfo.setCurrentDN("cn=admin-serv-buddha, ou=mcom.com, o=NetscapeRoot");
      consoleInfo.setLDAPConnection(connection);
         } catch (Exception e) {System.out.println(e); e.printStackTrace();}
     asp.initialize(consoleInfo);
         asp.migrate("c:\\netscape", "c:\\tmp", "cn=Server Group, cn=buddha.mcom.com, ou=mcom.com, o=NetscapeRoot", false);
     }*/

    /**
     * Implements the IProductObject interface. Initializes the page with
     * the global information.
     *
     * @param info - global information.
     */
    public void initialize(ConsoleInfo info) {
        _consoleInfo = info;
    }


    /**
      * Implements the IProductObject interface. Starts the Admin Server
      * migration process. Since there can only be one admin server per
      * admin group, migration always results in the overwriting of the
      * existing SIE. Also, since the admin server that is being invoked
      * to do the migration via URL belongs to the target config root,
      * the targetDN is also unused. Moreover, the server parameter is not
      * needed since there can only be one admin server per machine.
      *
      * @param  serverRoot - directory path for the migration origin.
      * @param  server - the server to migrate from the serverRoot.
      * @param  targetDN - the destination admin group DN.
      * @param  overwrite - whether to overwrite existing SIE.
      * @return  boolean value indicating whether the process succeeded (true)
      *          or failed (false).
      */
    public boolean migrate(String serverRoot, String server,
            String targetDN, boolean overwrite) {

        //ResourceSet resource = new ResourceSet("com.netscape.management.admserv.admserv");
        ResourceSet resource = AdminServer._resource;
        String adminURL = _consoleInfo.getAdminURL();
        if (adminURL == null || adminURL.equals("")) {
            Debug.println("ERROR AdminServerProduct.migrate: admin URL is not available.");
            return false;
        }

        if (migrateConfig(adminURL, serverRoot) == false) {
            Debug.println("ERROR AdminServerProduct.migrate: migrateConfig failed.");
            String msg = resource.getString("status", "migrateConfigFailed");
            String title = resource.getString("status", "migrateTitle");
            SuiOptionPane.showMessageDialog(null, msg, title,
                    SuiOptionPane.ERROR_MESSAGE);
            return false;
        }

        String msg = resource.getString("status", "migrateSucceeded");
        String title = resource.getString("status", "migrateTitle");
        SuiOptionPane.showMessageDialog(null, msg, title,
                SuiOptionPane.INFORMATION_MESSAGE);

        return true; // Success!
    }


    /**
      * Implements the IProductObject interface. Starts the Admin Server
      * creation process.
      *
      * @param  targetDN - the admin group DN where the new instance is to be
      *                    created.
      * @return  boolean value indicating whether the process succeeded (true)
      *          or failed (false).
      */
    public boolean createNewInstance(String targetDN) {
        Debug.println("trace AdminServerProduct.createNewInstance: not implemented.");
        return false;
    }


    protected boolean migrateConfig(String adminURL, String serverRoot) {

        String commandString =
                new String(adminURL + "admin-serv/tasks/operation/MigrateConfig" +
                "?oldServerRoot=" + URLByteEncoder.encodeUTF8(serverRoot));
        Debug.println(
                "TRACE AdminServerProduct.migrateConfig: MigrateConfig commandString = " +
                commandString);

        try {
            URL command = new URL(commandString);
            AdmTask task = new AdmTask(command,
                    _consoleInfo.getAuthenticationDN(),
                    _consoleInfo.getAuthenticationPassword());
            int execStatus = task.exec();
            if (execStatus != 0) {
                System.out.println("ERROR AdminServerProduct.migrateConfig: exec failed");
                return false;
            }
            int status = task.getStatus();
            if (status != 0) {
                System.out.println(
                        "ERROR AdminServerProduct.migrateConfig: exec status: " +
                        status + ": " + task.getResult("NMC_ErrInfo"));
                return false;
            }
        } catch (MalformedURLException e) {
            Debug.println(
                    "TRACE AdminServerProduct.migrateConfig: Bad URL: " + e);
            return false;
        }
        catch (Exception e) {
            Debug.println(
                    "TRACE AdminServerProduct.migrateConfig: unhandled exception: " + e);
            return false;
        }

        return true;
    }
}
