package gov.va.med.edp.weblogic;

import javax.naming.Context;

import org.apache.log4j.Logger;

import weblogic.jndi.Environment;
import weblogic.management.MBeanHome;
import weblogic.management.security.RealmMBean;
import weblogic.management.security.authentication.AuthenticationProviderMBean;
import weblogic.management.security.authentication.GroupEditorMBean;
import weblogic.management.security.authentication.GroupReaderMBean;
import weblogic.management.security.authentication.UserEditorMBean;
import weblogic.management.security.authentication.UserReaderMBean;

public class WeblogicUserManager {
	
    private static Logger logger = Logger.getLogger(WeblogicUserManager.class);
	private static final String SSL_GROUP_NAME = "SSL_AUTHENTICATED_USERS";	
	
	public static void addUserToWeblogicSecurity(String username)  {
		boolean userExists = false;
		try {            
			AuthenticationProviderMBean[] providers = getAuthenticationProviders();
			for (int i = 0; i < providers.length; i++) {
				if(logger.isDebugEnabled()){
					logger.debug("Available Authentication Provider # "+ i + " is " + providers[i].toString());
				}

				if ((providers[i].toString()).equalsIgnoreCase("Security:Name=myrealmDefaultAuthenticator")){
					if(logger.isDebugEnabled()){
						logger.debug("Using Authentication Provider: "+ providers[i].toString());
					}				
					if (providers[i] instanceof UserEditorMBean) {
						UserReaderMBean userReaderMBean = (UserReaderMBean) providers[i];
						userExists = userReaderMBean.userExists(username);
						}
				
					if(userExists) {
						if(logger.isDebugEnabled()) logger.debug("User: "+ username + " already exists in the weblogic security");
						return;
					} else {
						// create a new user and add him to the Group..
						if(logger.isDebugEnabled()) logger.debug("User: "+ username + " does not exists in the weblogic security. Adding new user to weblogic security");
													
						if (providers[i] instanceof UserEditorMBean) {
							UserEditorMBean userEditorMBean = (UserEditorMBean) providers[i];
								userEditorMBean.createUser(username, username, "EDIS BigBoard User: " + username);
								addUserToGroup(username);
						}				
					}
				}
			}			
		} catch (Exception e) { 
			logger.error("Exception Occurred while adding the user to weblogic security: "+ e);  
		}
 

	}	
	
	private static void addUserToGroup(String userName)  {
		boolean groupExists = false;
		try {            
			AuthenticationProviderMBean[] providers = getAuthenticationProviders();
			for (int i = 0; i < providers.length; i++) {
				if ((providers[i].toString()).equalsIgnoreCase("Security:Name=myrealmDefaultAuthenticator")){
					GroupReaderMBean groupReaderMBean = (GroupReaderMBean) providers[i];
					groupExists = groupReaderMBean.groupExists(SSL_GROUP_NAME);
					GroupEditorMBean groupEditorMBean = (GroupEditorMBean)providers[i];
					if (!groupExists){
						if(logger.isDebugEnabled()){
							logger.debug("Group: "+ SSL_GROUP_NAME + " does not exists in the weblogic security. Adding new group to weblogic security");
						}						
						groupEditorMBean.createGroup(SSL_GROUP_NAME, "EDIS SSL Group");
					}
					if(logger.isDebugEnabled()){
						logger.debug("Adding user: "+ userName + " to group: " + SSL_GROUP_NAME);
					}					
					groupEditorMBean.addMemberToGroup(SSL_GROUP_NAME, userName);
				}
			}			
		} catch (Exception e) { 
			logger.error("Exception Occurred while adding the user to the group: "+ e);  
		}
	}
	
	private static AuthenticationProviderMBean[] getAuthenticationProviders() throws Exception{
		Environment env = new Environment();            
		Context ctx = env.getInitialContext();
		MBeanHome home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);      
		RealmMBean securityRealm = home.getActiveDomain().getSecurityConfiguration().findDefaultRealm();		
		AuthenticationProviderMBean[] providers = securityRealm.getAuthenticationProviders();
		return providers;
	}
}
