package de.tudarmstadt.informatik.hostage.system;

import java.io.FileDescriptor;

import android.net.LocalServerSocket;
import android.net.LocalSocket;

/**
 * Receives a file descriptor through a unix domain socket.
 * 
 * @author Mihai Plasoianu
 */
public class P implements Runnable {

	/**
	 * Path for UDS in abstract namespace.
	 */
	private final static String NAME = "hostage";

	/**
	 * Port to bind.
	 */
	private int port;

	public P(int port) {
		this.port = port;
	}

	/**
	 * Start p, wait for connection and receive a file descriptor.
	 */
	public FileDescriptor bindAndGetFD() {
		FileDescriptor fd = null;
		try {
			new Thread(this).start();
			LocalServerSocket localServer = new LocalServerSocket(NAME);
			LocalSocket localSocket = localServer.accept();
			while (localSocket.getInputStream().read() != -1)
				;
			FileDescriptor[] fdArray;
			fdArray = localSocket.getAncillaryFileDescriptors();
			if (fdArray != null) {
				fd = fdArray[0];
			}
			localSocket.close();
			localServer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fd;
	}

	/**
	 * Run p in separate Thread.
	 */
	@Override
	public void run() {
		Process p;
		try {
			String command = String.format("/data/local/p %d", port);
			p = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
			p.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}