import java.io.*;
import java.lang.reflect.*;

public final class GremlinWorrier {
    private static ThreadGroup gremlins;
    private static String gremlinDir;
	
    private GremlinWorrier() {}	
    // private - we don't want any gremlins instantiating it
	
    public static void main(String[] args) {

	if (args.length == 0) {
	    throw new RuntimeException("\n-> Usage: java GremlinWorrier dir");
	}

	File dir = new File(args[0]);

	if (!(dir.exists() && dir.isDirectory())) {
	    throw new RuntimeException("\n-> Usage: java GremlinWorrier dir");
	}

	gremlinDir = dir.getAbsolutePath();

	// Create the gremlin security manager, and a 
	// thread group for any gremlins to run it.
	SecurityManager sm = new GremlinWatcher(
		Thread.currentThread().getThreadGroup(), gremlinDir);
	System.setSecurityManager(sm);

	gremlins = new ThreadGroup("Gremlins");

	BufferedReader in = new BufferedReader(
		new InputStreamReader(System.in));

	System.out.print(
		"-> Please specify name of service you want to start.\n"
		+ "-> Default options: BadGremlin, GoodGremlin.\n"
		+ "--> ");

	try {

	    String serviceName = in.readLine();
	    Class serviceType = Class.forName(serviceName);
	    Constructor serviceCtr =
		    serviceType.getConstructor(new Class[] {String.class});
	    Runnable gremlin = (Runnable)
		    serviceCtr.newInstance(new Object[] {gremlinDir});

	    // Create a new thread for gremlin, in the 
	    // gremlin's thread group. Within that thread 
	    // group, they can do whatever they want!
	    Thread t = new Thread(gremlins, gremlin);
	    t.start();
	    Thread.currentThread().sleep(100);
	} catch (Exception e) {
	    e.printStackTrace();
	}
	System.out.flush();
    }
}

