/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.tools.upgrade;

import java.io.*;
import java.util.logging.*;

import com.sun.enterprise.tools.upgrade.cli.*;
import com.sun.enterprise.tools.upgrade.common.*;
import com.sun.enterprise.tools.upgrade.gui.MainFrame;
import com.sun.enterprise.tools.upgrade.gui.util.*;
import com.sun.enterprise.util.i18n.StringManager;
import com.sun.enterprise.tools.upgrade.logging.*;
import com.sun.enterprise.util.ASenvPropertyReader;
import com.sun.enterprise.util.SystemPropertyConstants;

public class UpgradeToolMain {
    
    static{
        String domainRoot = System.getProperty("com.sun.aas.domainRoot");
        if(domainRoot == null){
            System.out.println("Configuration Error: AS_DEFS_DOMAINS_PATH is not set.");
            System.exit(1);
        }
        String upgradeLogPath =domainRoot+File.separator+"upgrade.log";
        try{
            File f = new File(domainRoot);
            if(!f.exists()){
                System.out.println("Configuration Error: AS_DEFS_DOMAINS_PATH: "+ domainRoot + " does not exist.");
                System.exit(1);
            }
            LogService.initialize(upgradeLogPath);
        }catch(Exception e){
            System.out.println("Could not create upgrade.log file: " + e.getLocalizedMessage());
        }
    }
    
    static Logger _logger=LogService.getLogger(LogService.UPGRADE_LOGGER);
    private CommonInfoModel commonInfo;
    private UpgradeHarness harness;
    private String certDbPassword;
    private String aliasname;
    private String keyStorePassword;
    private StringManager sm;
    public UpgradeToolMain() {
        final ASenvPropertyReader reader = new ASenvPropertyReader(
           System.getProperty(SystemPropertyConstants.CONFIG_ROOT_PROPERTY));
       reader.setSystemProperties();

        sm = StringManager.getManager(LogService.UPGRADE_LOGGER);
        _logger.log(Level.INFO, sm.getString("enterprise.tools.upgrade.start_upgrade_tool"));
        commonInfo = new CommonInfoModel();
        String targetDomainRoot = System.getProperty("com.sun.aas.domainRoot");
        if(targetDomainRoot == null) {
           targetDomainRoot = new File("").getAbsolutePath();
        }
        commonInfo.setTargetDomainRoot(targetDomainRoot);
        String targetVersion = System.getProperty("com.sun.aas.utool.targetVersion");
	if(targetVersion != null){
            _logger.info("asupgrade " + targetVersion);
            commonInfo.setTargetVersionAndEdition(targetVersion);
            if(!targetVersion.equalsIgnoreCase(UpgradeConstants.VERSION_AS90_PE)){
                commonInfo.setMasterPassword("");
            }
        } else {
            _logger.log(Level.SEVERE, sm.getString("enterprise.tools.upgrade.nullTargetError"));
            System.exit(1);
        }
        
        harness = new UpgradeHarness();
        commonInfo.setOSName(System.getProperty("os.name"));
        String targetInstallPath = System.getProperty("com.sun.aas.installRoot");
        //Test for valid configuration by checking installRoot
        String osName = System.getProperty("os.name");
        String asenv = null;
        String asadmin = null;
        if(osName.indexOf("Windows") != -1)
            asadmin = targetInstallPath + File.separator + "bin" + File.separator + "asupgrade.bat";
        else
            asadmin = targetInstallPath + File.separator + "bin" + File.separator + "asupgrade";
        try {
            if(! new File(asadmin).exists()) {
                _logger.log(Level.WARNING,sm.getString("enterprise.tools.upgrade.configError"));
                System.exit(1);
            }
        }catch (Exception e) {
            _logger.log(Level.WARNING,sm.getString("enterprise.tools.upgrade.unknownError"),e);
        }
        commonInfo.setTargetInstallDir(targetInstallPath);
    }
    public void startGUI(String [] args){
        _logger.log(Level.INFO,sm.getString("enterprise.tools.upgrade.start_upgrade_tool_gui"));
        if(args.length > 0){
            CliLogMessageListener l = new CliLogMessageListener();
            LogService.addLogMessageListener(l);  //to log and output command line parsing
            new ArgsParser(args, commonInfo).parse();
            LogService.removeLogMessageListener(l);
        }
        MainFrame gui = new MainFrame(commonInfo);
        LogService.addLogMessageListener(gui);
        gui.addDialogListener(new DialogListener(){
            public void dialogProcessed(DialogEvent evt){
                processUIEvent(evt);
            }
        });
        UpdateProgressManager.getProgressManager().addUpgradeUpdateListener(gui);
        gui.setVisible(true);
    }
    
    public void startCLI(String [] args){
        _logger.log(Level.INFO,sm.getString("enterprise.tools.upgrade.start_upgrade_tool_cli"));
        LogService.addLogMessageListener(new CliLogMessageListener());        
        try{
            CLIParser parser = new CLIParser(commonInfo, args);
        }catch(Exception e){
            _logger.log(Level.INFO,sm.getString("enterprise.tools.upgrade.unexpected_parsing"),e);
            System.exit(1);
        }
        this.upgrade();
    }
    
    private void processUIEvent(DialogEvent evt){
        if(evt.getAction() == DialogEvent.FINISH_ACTION ||
        evt.getAction() == DialogEvent.CANCEL_ACTION){
            System.exit(0);
        }else if(evt.getAction() == DialogEvent.UPGRADE_ACTION){
            this.upgrade();
        }
    }
    
    private void upgrade(){
        harness.setCommonInfoModel(commonInfo);
        _logger.log(Level.INFO,sm.getString("enterprise.tools.upgrade.start_upgrade_harness"));
        harness.startUpgrade();
        commonInfo.deletePasswordFile();
    }
    
    public static void main(String [] args) {
        UpgradeToolMain main = new UpgradeToolMain();
        StringBuffer argsStringBuff = new StringBuffer();
        for(int i=0;i<args.length;i++){
            argsStringBuff.append(args[i]);
            argsStringBuff.append(" ");
        }
        _logger.info("asupgrade " + argsStringBuff.toString());
        if(args.length==0){
            main.startGUI(args);
        } else if (args[0].equals("-c") || args[0].equals("--console")|| args[0].equals("-V")|| args[0].equals("--version")){
            //start CLI
            main.startCLI(args);
        } else {
            main.startGUI(args);
        }
    }
}
