// package pic20b;


import java.io.*;


class GremlinWatcher extends SecurityManager {

    private ThreadGroup seniorThreadGroup;
    private String gremlinDir;

    public GremlinWatcher(ThreadGroup seniorThreadGroup, String gremlinDir) {
	super();
	this.seniorThreadGroup = seniorThreadGroup;
	this.gremlinDir = gremlinDir;
    }

    public void checkAccess(Thread t) {
	super.checkAccess(t);
	if (! threadGroupAccessAllowed(t.getThreadGroup())) {
	    checkPermission(new RuntimePermission("modifyThread"));
	}
    }

    public void checkAccess(ThreadGroup g) {
	super.checkAccess(g);
	ThreadGroup tg = Thread.currentThread().getThreadGroup();
	if (! threadGroupAccessAllowed(g)) {
	    checkPermission(new RuntimePermission("modifyThreadGroup"));
	}
    }

    /**
     * Implements our thread access policy. This is our
     * own method.
     */
    protected boolean threadGroupAccessAllowed(ThreadGroup g) {
	ThreadGroup tg = Thread.currentThread().getThreadGroup();
	return (tg.parentOf(g));
    }

    public void checkWrite(String fileName) {
	ThreadGroup tg = Thread.currentThread().getThreadGroup();

	if (tg != seniorThreadGroup) {

	    // Perform checks; if checks fail, throw exception
	    File f = new File(fileName);
	    String path = f.getAbsolutePath();
	    if (! path.regionMatches(true, 0, gremlinDir + File.separator, 0,
		    gremlinDir.length() + 1)) {
		// Cannot write file outside of Gremlin Directory
		super.checkWrite(fileName);
	    }
			
	    if (f.getName().regionMatches(true, f.getName().length() - 8,
		    ".private", 0, 8)) {
		// Cannot write private file
		super.checkWrite(fileName);
	    }
	}
		
	// return ok
	System.out.println("File " + fileName + " may be written");
    }

}
