/*
 * 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.
 */

/*
 * ConfigTransfers.java
 *
 * Created on September 8, 2003, 9:05 AM
 */

package com.sun.enterprise.tools.upgrade.miscconfig;

/**
 *
 * @author  prakash
 * @author hans hrasna
 * This class is used to transfer config files
 * server.policy, sun-acc.xml, default-web.xml, secmod.db
 * with minor modifications wherever necessary.
 */
import com.sun.enterprise.tools.upgrade.common.*;
import java.io.*;
import com.sun.enterprise.util.i18n.StringManager;
import com.sun.enterprise.tools.upgrade.logging.*;
import java.util.logging.*;
import java.util.Enumeration;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.Vector;

public class ConfigTransfers implements BaseModule{
    
    private static final String SECMODDB = "secmod.db";
    
    private StringManager stringManager = StringManager.getManager("com.sun.enterprise.tools.upgrade.miscconfig");
    private Logger logger = CommonInfoModel.getDefaultLogger();
    private Vector recoveryList = new Vector();
    
    /** Creates a new instance of ConfigTransfers
     *
     */
    public ConfigTransfers() {
        
    }
    
    public boolean upgrade(CommonInfoModel commonInfo) {
        transferServerPolicy(commonInfo.getSourceServerPolicyFileName(), commonInfo.getTargetServerPolicyFileName());
        //transferSecModDb(commonInfo);
        new DefaultWebXMLTransfer().transform(commonInfo.getSourceDefaultWebXMLFileName(), commonInfo.getTargetDefaultWebXMLFileName());
        new SunACCTransfer().transform(commonInfo.getSourceSunACCFileName(), commonInfo.getTargetSunACCFileName());
        
        if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)){
            new InitConfTransfer(commonInfo).transform();
            
        }else{
            // For 8.x still need to figure out what need to be transferred.
            // FIXME
        }
        return true;
    }
    
    public void recovery(CommonInfoModel commonInfo) {
        Enumeration e = recoveryList.elements();
        while(e.hasMoreElements()){
            String recoverPath = (String)e.nextElement();
            String backupPath = recoverPath + ".bak";
            try {
                UpgradeUtils.getUpgradeUtils(commonInfo).copyFile(backupPath, recoverPath);
                new File(backupPath).delete();
            } catch (IOException ioe) {
                logger.log(Level.SEVERE, stringManager.getString("upgrade.realm.recoveryFailureMessage",ioe.getMessage()),new Object[]{recoverPath,ioe});
            }
        }
    }
    
    /* transferSeverPolicy uses sun.security.provider.PolicyParser from the jdk to parse the source and
     * target server.policy files and transfer user added grants and permissions
     * @author  hans
     *
     */
    private void transferServerPolicy(String sourcePolicyFileName, String destPolicyFileName){
        if (!backup(destPolicyFileName)) {
            logger.log(Level.SEVERE, stringManager.getString("upgrade.configTransfers.serverPolicy.backupFailureMessage"));
            logger.log(Level.SEVERE, stringManager.getString("upgrade.configTransfers.serverPolicy.startFailureMessage"));
            return;
        }
        logger.log(Level.INFO, stringManager.getString("upgrade.configTransfers.serverPolicy.startMessage"));
        PolicyParser sourcePolicy = new PolicyParser();
        PolicyParser targetPolicy = new PolicyParser();
        try {
            sourcePolicy.read(new FileReader(sourcePolicyFileName));
            targetPolicy.read(new FileReader(destPolicyFileName));
        } catch (PolicyParser.ParsingException pe) {
            logger.log(Level.SEVERE, stringManager.getString("upgrade.configTransfers.serverPolicy.startFailureMessage") + pe.getLocalizedMessage());
            return;
        } catch (IOException ioe) {
            logger.log(Level.SEVERE, stringManager.getString("upgrade.configTransfers.serverPolicy.startFailureMessage"),ioe.getMessage());
            return;
        }
        Enumeration sourceElements = sourcePolicy.grantElements();
        Enumeration targetElements = targetPolicy.grantElements();
        
        while(sourceElements.hasMoreElements()) {
            PolicyParser.GrantEntry sourceGrantEntry = (PolicyParser.GrantEntry)sourceElements.nextElement();
            boolean matchedGrantEntry = false;
            while (targetElements.hasMoreElements()) {
                PolicyParser.GrantEntry targetGrantEntry = (PolicyParser.GrantEntry)targetElements.nextElement();
                if(targetGrantEntry.codeBase == null && sourceGrantEntry.codeBase == null) {
                    matchedGrantEntry = true;
                } else if (targetGrantEntry.codeBase != null && sourceGrantEntry.codeBase != null) {
                    if (targetGrantEntry.codeBase.equals(sourceGrantEntry.codeBase)) {
                        //found a matched codeBase
                        matchedGrantEntry = true;
                    }
                }
                if(matchedGrantEntry) {
                    //does the target have all the permissions of the source? if not, add the missing permissions
                    Enumeration sourcePermissions = sourceGrantEntry.permissionElements();
                    while(sourcePermissions.hasMoreElements()) {
                        boolean matchedPermission = false;
                        PolicyParser.PermissionEntry sourcePermission = (PolicyParser.PermissionEntry)sourcePermissions.nextElement();
                        /*if(!targetGrantEntry.contains(sourcePermission)){
                            targetGrantEntry.add(sourcePermission);
                        }*/
                        Enumeration targetPermissions = targetGrantEntry.permissionElements();
                        while(targetPermissions.hasMoreElements()) {
                            PolicyParser.PermissionEntry targetPermission = (PolicyParser.PermissionEntry)targetPermissions.nextElement();
                            if(targetPermission.equals(sourcePermission)) {
                                matchedPermission = true;
                                break;
                            }
                        }
                        if(!matchedPermission){
                            targetGrantEntry.add(sourcePermission);
                        }
                    }
                    //does the target have all the principals of the source? if not, add the missing principals
                    Iterator sourcePrincipalIterator = sourceGrantEntry.principals.iterator();
                    while(sourcePrincipalIterator.hasNext()) {
                        boolean matchedPrincipal = false;
                        PolicyParser.PrincipalEntry sourcePrincipalEntry = (PolicyParser.PrincipalEntry)sourcePrincipalIterator.next();
                        /*if(!targetGrantEntry.contains(sourcePrincipalEntry)) {
                            targetGrantEntry.principals.add(sourcePrincipalEntry);
                        }*/
                        Iterator targetPrincipalIterator = targetGrantEntry.principals.iterator();
                        while(targetPrincipalIterator.hasNext()) {
                            PolicyParser.PrincipalEntry targetPrincipalEntry = (PolicyParser.PrincipalEntry)targetPrincipalIterator.next();
                            if(targetPrincipalEntry.equals(sourcePrincipalEntry)) {
                                matchedPrincipal = true;
                                break;
                            }
                        }
                        if(!matchedPrincipal) {
                            targetGrantEntry.principals.add(sourcePrincipalEntry);
                        }
                    }
                    break;
                }
            }
            if (!matchedGrantEntry) {
                targetPolicy.add(sourceGrantEntry);
            }
        }
        try {
            targetPolicy.write(new FileWriter(destPolicyFileName));
        } catch (IOException ioe) {
            logger.log(Level.SEVERE, stringManager.getString("upgrade.configTransfers.serverPolicy.startFailureMessage"),ioe.getMessage());
            return;
        }
    }
    
    private void transferSecModDb(CommonInfoModel commonInfo) {
        String sourcePath = commonInfo.getSourceDomainPath();
        String targetPath = commonInfo.getDestinationDomainPath();
        File sourceFile = new File(sourcePath + File.separator + "config" + File.separator + SECMODDB);
        File targetFile = new File(targetPath + File.separator + "config" + File.separator + SECMODDB);
        if(!sourceFile.exists()) return;
        if(targetFile.exists()) {
            backup(targetFile.getAbsolutePath());
        }
        try {
            UpgradeUtils.getUpgradeUtils(commonInfo).copyFile(sourceFile.getAbsolutePath(), targetFile.getAbsolutePath());
        } catch(IOException e) {
            logger.log(Level.WARNING, stringManager.getString("upgrade.configTransfers.secModDb.failureMessage") + e.getLocalizedMessage());
        }
    }
    
    private boolean backup(String filename) {
        try{
            File targetFile = new File(filename);
            boolean renamed = targetFile.renameTo(new File(filename +".bak"));
            if(!renamed){
                // This is possible if user is running the upgrade again and .bak is already created.
                renamed = targetFile.delete();
            }
            if(renamed){
                targetFile = new File(filename);
                targetFile.createNewFile();
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename + ".bak")));
                PrintWriter writer = new PrintWriter(new FileOutputStream(targetFile));
                String readLine = null;
                while((readLine = reader.readLine()) != null){
                    writer.println(readLine);
                }
                writer.flush();
                writer.close();
                reader.close();
                return true;
                //permission javax.security.auth.PrivateCredentialPermission "javax.resource.spi.security.PasswordCredential * \"*\"","read
                // The above line differs from source.  Still need to be modified.
            }else{
                // Log a error message
                logger.log(Level.SEVERE, stringManager.getString("upgrade.configTransfers.serverPolicy.renameFailureMessage"));
            }
        }catch(Exception ex){
            // Log a error message
            logger.log(Level.SEVERE, stringManager.getString("upgrade.configTransfers.serverPolicy.startFailureMessage"),ex);
        }
        return false;
    }
    
    /*
    public static void main(String[] args){
        try{
            com.sun.enterprise.tools.upgrade.logging.LogService.initialize("upgradetest.log");
        }catch(Exception e){
            e.printStackTrace();
        }
        CommonInfoModel cim = new CommonInfoModel();
        cim.setSourceInstallDir("C:\\Sun\\AppServer80PE");
        cim.setTargetInstallDir("C:\\Sun\\AppServer81");
        cim.setCurrentDomain("domain1");
        cim.setCurrentSourceInstance("server1");
        cim.setTargetDomainRoot("C:\\Sun\\AppServer81\\domains");
        java.util.Hashtable ht = new java.util.Hashtable();
        ht.put("domain1", "C:\\Sun\\AppServer7\\domains\\domain1");
        cim.setDomainMapping(ht);
        cim.enlistDomainsFromSource();
        cim.setAdminPassword("adminadmin");
        new ConfigTransfers().upgrade(cim);
    }
     */
    
    public String getName() {
        return stringManager.getString("upgrade.configTransfers.moduleName");
    }
    
}
