#include "devfs.h"
#include "fs.h"
#include "process.h"

fd_t sys_open(char *fn, uchar mode) {
	// Only devices for now...
	
//	printf("sys_open(0x%x, %d);\n", fn, mode);
	
	if (strncmp(fn, "/dev/", 5) != 0) {
		printf(" FS: Only devices for now...\n");
		return -1;
	}
	
	int i;

	for (i = 0; i < devfs_ndevs; i++) {
		if (strcmp(fn + 5, devfs_devices[i].name) == 0) {
			if (devfs_devices[i].fo->opener == 0) {
				devfs_devices[i].fo->opener = cur_proc->pid;
				fd_t fd = cur_proc->proc->n_fds++;
				cur_proc->proc->fd_table[fd] = devfs_devices[i].fo;

				return fd;
			} else {
				printf(" FS: Device already in use\n");

				return -1;
			}
		}
	}

	printf(" FS: No such device!\n");

	return -1;
}

void sys_close(fd_t fd) {
	printf("sys_close: nop\n");
}

int sys_read(fd_t fd, void *buf, size_t n) {
	struct file_object *fo = cur_proc->proc->fd_table[fd];
	return fo->fops->read(fo, buf, n);
}

int sys_write(fd_t fd, void *buf, size_t n) {
	struct file_object *fo = cur_proc->proc->fd_table[fd];
	return fo->fops->write(fo, buf, n);
}
