/* usage: loadfile unix-path postfs-path bufsize(in bytes) */
#include <sys/file.h>
#include "tmp/libpq-fs.h"
#include "catalog/pg_lobj.h"

extern char *PQexec();

void main(ac,av)
     int ac;
     char *av[];
{
    int fd, pfd;
    int n, pn;
    int blen = 65536;
    char *buf;
    char *res;

    PQsetdb(getenv("USER"));
    if (ac != 3) {
	printf ("usage: %s unix-path postfs-path\n",av[0]);
	exit(1);
    }

    buf = (char *)malloc(blen);

    res = PQexec("begin");
    if (p_open(av[2],O_RDONLY) < 0) {
	fd = open(av[1],O_RDONLY);
	pfd = p_creat(av[2],0666,Unix);
	while ((n = read(fd,buf,blen)) > 0) {
	    if ((pn = p_write(pfd,buf,n)) != n) {
		printf("expected %d, got %d\n", n, pn);
	    }
	    printf ("p_write returned %d\n",pn);
	}
	close(fd);
	p_close(pfd);
    } else {
	printf ("file already exists\n");
    }
    res = PQexec("end");
    PQfinish();
    exit(0);
}
