package binarydeployer;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements BundleActivator {

	public void start(BundleContext context) throws Exception {
		System.out.println("BinaryDeployer bundle started");
		String filename = context.getBundle().getLocation().substring(5);
		System.out.println(filename);

		try {
			// Open the ZIP file

			ZipInputStream in = new ZipInputStream(
					new FileInputStream(filename));
			ZipEntry entry = in.getNextEntry();
			while (!(entry.getName().endsWith("tar"))) {
				entry = in.getNextEntry();

			}

			// Open the output file
			String outFilename = "/tmp/tarball.tar";
			OutputStream out = new FileOutputStream(outFilename);

			// Transfer bytes from the ZIP file to the output file
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}

			// Close the streams
			out.close();
			in.close();

			//do the actual extraction of the tarball
			Runtime.getRuntime().exec("tar -C / -xvf " + outFilename);
			Runtime.getRuntime().exec("rm -fr " + outFilename);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void stop(BundleContext context) throws Exception {
		System.out.println("BinaryDeployer bundle stopped");

	}
}