#include <sys/types.h>
#include <dirent.h>
#include <sys/time.h> 
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>

#define NODEFINE
#include <u.h>
#include <libc.h>
#include <fcall.h>
#include "fd.h"

int
pm_create(char *file, int mode, ulong perm)
{
	int m, type, ufd;
	char *path;
	File *f;

//	rlock(&dotlock);
	if((path = pm_openpath(file)) == nil){
//		runlock(&dotlock);
		return -1;
	}
	if(perm&PM_DMDIR){
		if(mode != PM_OREAD){
//			runlock(&dotlock);
			pm_werrstr("invalid mode");
			return -1;
		}
		if(mkdir(file, perm) < 0){
//			runlock(&dotlock);
			pm_oserror();
			return -1;
		}
		if((ufd = open(file, O_RDONLY, perm)) < 0){
//			runlock(&dotlock);
			pm_oserror();
			return -1;
		}
		type = Tdir;
	}else{
		m = (mode&3)|O_CREAT;
		if(mode&PM_OEXCL)
			m |= O_EXCL;
		else
			m |= O_TRUNC;
		if((ufd = open(file, m, perm)) < 0){
			pm_oserror();
			return -1;
		}
		type = Tfile;
	}
	if((f = pm_allocfile(ufd)) == nil){
		close(ufd);
		return -1;
	}
	f->type = type;
	f->mode = mode;
	f->ufd = ufd;
	f->path = path;
	pm_qunlock(&f->lk);
	return ufd;
}
