/**
 * 
 */
package org.apache.guacamole.auth.tacacs.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.net.auth.credentials.CredentialsInfo;
import org.apache.guacamole.net.auth.credentials.GuacamoleInvalidCredentialsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author TELMEX
 */
public class AuthenticationTacacs {
    /**
     * Logger for this class.
     */
    private static final Logger logger = LoggerFactory.getLogger(AuthenticationTacacs.class);
	/**
	 * Method executes perl script 'accessTacacs.pl' to get TACACS's authentication
	 * @param user 
	 * @param password
	 * @param ipAddress LoggableAddress
	 * @return true - When script execution result returns string 'Granted'
	 * @throws GuacamoleException 
	 */
	public static boolean authenticate(String user, String password, String ipAddress) throws GuacamoleException {
		boolean result = false;
		if (user.length() > 0 && password.length() > 0) {
			String line;
			Process process = null;
			InputStream stdout = null;
			BufferedReader reader = null;
			InputStreamReader inReader = null;
			try {
				process = Runtime.getRuntime().exec("/home/admin-cns/Scripts/accessTacacs.pl "
						  + "-u " + user + " -p " + password + " -a " + ipAddress);
				process.waitFor();
				stdout = process.getInputStream();
				inReader = new InputStreamReader(stdout);
				reader = new BufferedReader(inReader);
				while ((line = reader.readLine()) != null) {
					if (line != null && line.indexOf("Granted") != -1) {
						result = true;
					} else {
						if (line.indexOf("Can't open") != -1) {
							throw new GuacamoleException(line);
						}
					}
				}
			} catch (Exception e) {
				logger.error(Utils.getStackTrace(e));
				throw new GuacamoleInvalidCredentialsException(
						"Error reported by Tacacs:[" + e.getMessage() + "]",
						CredentialsInfo.USERNAME_PASSWORD);
			} finally {
				try {
					reader.close();
				} catch (IOException e) {
					logger.error(Utils.getStackTrace(e));
				}
				try {
					inReader.close();
				} catch (IOException e) {
					logger.error(Utils.getStackTrace(e));
				}
				try {
					stdout.close();
				} catch (IOException e) {
					logger.error(Utils.getStackTrace(e));
				}
				if (process != null) {
					process.destroy();
					process.destroyForcibly();
				}
			}
		} else {
			throw new GuacamoleInvalidCredentialsException(
					"Tacacs authentication attempt cannot be done with a missing user.",
					CredentialsInfo.USERNAME_PASSWORD);
		}
		return result;
	}
}
