/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.sh.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Properties;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

import net.morilib.sh.ShEnvironment;
import net.morilib.sh.ShFileSystem;
import net.morilib.sh.ShProcess;

public class ShJarProcess implements ShProcess {

	public int main(ShEnvironment env, ShFileSystem fs,
			InputStream stdin, PrintStream stdout,
			PrintStream stderr, String... args) throws IOException {
		URLClassLoader c;
		Attributes a;
		Manifest m;
		Class<?> k;
		JarFile j;
		Method t;
		String n;
		File f;
		URL l;

		try {
			f = new File(args[0]);
			j = new JarFile(f);
			m = j.getManifest();
			a = m.getMainAttributes();
			n = a.getValue("Jsh-Main-Class");
			l = f.getCanonicalFile().toURI().toURL();
			c = new URLClassLoader(new URL[] { l });
			k = c.loadClass(n);
			t = k.getMethod("jshmain",
					Properties.class,
					InputStream.class,
					PrintStream.class,
					PrintStream.class,
					Object[].class);
			return ((Integer)t.invoke(
					null,
					env.toProperties(),
					stdin,
					stdout,
					stderr,
					new Object[] { args })).intValue();
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		}
	}

}
