/*
 * Copyright (c) 2006 Jakub Jermar
 * Copyright (c) 2008 Jiri Svoboda
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * - The name of the author may not be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/** @addtogroup libc
 * @{
 */
/** @file
 */ 

#include <task.h>
#include <ipc/ipc.h>
#include <ipc/loader.h>
#include <libc.h>
#include <string.h>
#include <async.h>
#include <errno.h>

task_id_t task_get_id(void)
{
	task_id_t task_id;

	(void) __SYSCALL1(SYS_TASK_GET_ID, (sysarg_t) &task_id);

	return task_id;
}

static int task_spawn_loader(void)
{
	int phone_id, rc;

	rc = __SYSCALL1(SYS_TASK_SPAWN, (sysarg_t) &phone_id);
	if (rc != 0)
		return rc;

	return phone_id;
}

/** Create a new task by running an executable from VFS.
 *
 * @param path	pathname of the binary to execute
 * @param argv	command-line arguments
 * @return	ID of the newly created task or zero on error.
 */
task_id_t task_spawn(const char *path, const char *argv[])
{
	int phone_id;
	ipc_call_t answer;
	aid_t req;
	int rc;

	/* Spawn a program loader */	
	phone_id = task_spawn_loader();
	if (phone_id < 0) return 0;

	/*
	 * Say hello so that the loader knows the incoming connection's
	 * phone hash.
	 */
	rc = async_req_0_0(phone_id, LOADER_HELLO);
	if (rc != EOK) return 0;

	/* Send program pathname */
	req = async_send_0(phone_id, LOADER_SET_PATHNAME, &answer);
	rc = ipc_data_write_start(phone_id, (void *)path, strlen(path));
	if (rc != EOK) {
		async_wait_for(req, NULL);
		return 1;
	}

	async_wait_for(req, &rc);
	if (rc != EOK) return 0;

	/* Request loader to start the program */	
	rc = async_req_0_0(phone_id, LOADER_RUN);
	if (rc != EOK) return 0;

	ipc_hangup(phone_id);

	return 1;
}

/** @}
 */
