/*
 * @(#)Debug.java	1.5 00/01/11
 *
 * Copyright 2000 Sun Microsystems, Inc. All rights reserved.
 * Copyright 2000 Sun Microsystems, Inc. Tous droits reserves.
 */

package javax.security.auth;


/**
 * A utility class for debuging.
 *
 * @version 1.7
 * @author Roland Schemers
 */
class Debug {

    private String prefix;

    private static String args;

    static {
	args = (String) java.security.AccessController.doPrivileged
		(new java.security.PrivilegedAction() {
		public Object run() {
		    return System.getProperty("java.security.auth.debug");
		}
	});
	if (args != null) {
	    args = args.toLowerCase();
	    if (args.equals("help")) {
		Help();
	    }
	}
    }

    public static void Help() 
    {
	System.err.println();
	System.err.println("all   all JAAS debugging");
	System.err.println("logincontext   login context debugging");
	System.err.println("policy   Subject-based policy");
	System.err.println("auth   Subject-based access control");
	System.err.println("combiner   Subject-based domain combiner");
	System.err.println();
	System.exit(0);
    }

    /**
     * Get a Debug object corresponding to whether or not the given
     * option is set. Set the prefix to be the same as option.
     */

    public static Debug getInstance(String option)
    {
	return getInstance(option, option);
    }

    /**
     * Get a Debug object corresponding to whether or not the given
     * option is set. Set the prefix to be prefix.
     */
    public static Debug getInstance(String option, String prefix)
    {
	if (isOn(option)) {
	    Debug d = new Debug();
	    d.prefix = prefix;
	    return d;
	} else {
	    return null;
	}
    }

    /**
     * True if the system property "security.debug" contains the 
     * string "option".
     */
    public static boolean isOn(String option)
    {
	if (args == null)
	    return false;
	else {
	    if (args.indexOf("all") != -1)
		return true;
	    else 
		return (args.indexOf(option) != -1);
	}
    }

    /**
     * print a message to stderr that is prefixed with the prefix
     * created from the call to getInstance.
     */

    public void println(String message)
    {
	System.err.println(prefix + ": "+message);
    }

    /**
     * print a blank line to stderr that is prefixed with the prefix.
     */

    public void println()
    {
	System.err.println(prefix + ":");
    }

    /**
     * print a message to stderr that is prefixed with the prefix.
     */

    public static void println(String prefix, String message)
    {
	System.err.println(prefix + ": "+message);
    }
}
