/*
  FUSE: Filesystem in Userspace
  Copyright (C) 2001-2007  Miklos Szeredi <miklos@szeredi.hu>

  This program can be distributed under the terms of the GNU GPL.
  See the file COPYING.

  gcc -Wall `pkg-config fuse --cflags --libs` hello_ll.c -o hello_ll
*/

#define FUSE_USE_VERSION 26

#include <fuse/fuse_lowlevel.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <gtk/gtk.h>
#include <glib.h>
#include <glib/gstdio.h>

static const char *hello_str = "Hello World!\n";
static const char *hello_name = "hello";

static int hello_stat(fuse_ino_t ino, struct stat *stbuf)
{
	stbuf->st_ino = ino;
	switch (ino) {
	case 1:
		stbuf->st_mode = S_IFDIR | 0755;
		stbuf->st_nlink = 2;
		break;

	case 2:
		stbuf->st_mode = S_IFREG | 0444;
		stbuf->st_nlink = 1;
		stbuf->st_size = strlen(hello_str);
		break;

	default:
		return -1;
	}
	return 0;
}

static void hello_ll_getattr(fuse_req_t req, fuse_ino_t ino,
			     struct fuse_file_info *fi)
{
	struct stat stbuf;

	(void) fi;

	memset(&stbuf, 0, sizeof(stbuf));
	if (hello_stat(ino, &stbuf) == -1)
		fuse_reply_err(req, ENOENT);
	else
		fuse_reply_attr(req, &stbuf, 1.0);
}

static void hello_ll_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
{
	struct fuse_entry_param e;

	if (parent != 1 || strcmp(name, hello_name) != 0)
		fuse_reply_err(req, ENOENT);
	else {
		memset(&e, 0, sizeof(e));
		e.ino = 2;
		e.attr_timeout = 1.0;
		e.entry_timeout = 1.0;
		hello_stat(e.ino, &e.attr);

		fuse_reply_entry(req, &e);
	}
}

struct dirbuf {
	char *p;
	size_t size;
};

static void dirbuf_add(fuse_req_t req, struct dirbuf *b, const char *name,
		       fuse_ino_t ino)
{
	struct stat stbuf;
	size_t oldsize = b->size;
	b->size += fuse_add_direntry(req, NULL, 0, name, NULL, 0);
	b->p = (char *) realloc(b->p, b->size);
	memset(&stbuf, 0, sizeof(stbuf));
	stbuf.st_ino = ino;
	fuse_add_direntry(req, b->p + oldsize, b->size - oldsize, name, &stbuf,
			  b->size);
}

#define min(x, y) ((x) < (y) ? (x) : (y))

static int reply_buf_limited(fuse_req_t req, const char *buf, size_t bufsize,
			     off_t off, size_t maxsize)
{
	if (off < bufsize)
		return fuse_reply_buf(req, buf + off,
				      min(bufsize - off, maxsize));
	else
		return fuse_reply_buf(req, NULL, 0);
}

static void hello_ll_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
			     off_t off, struct fuse_file_info *fi)
{
	(void) fi;

	if (ino != 1)
		fuse_reply_err(req, ENOTDIR);
	else {
		struct dirbuf b;

		memset(&b, 0, sizeof(b));
		dirbuf_add(req, &b, ".", 1);
		dirbuf_add(req, &b, "..", 1);
		dirbuf_add(req, &b, hello_name, 2);
		reply_buf_limited(req, b.p, b.size, off, size);
		free(b.p);
	}
}

static void hello_ll_open(fuse_req_t req, fuse_ino_t ino,
  struct fuse_file_info *fi)
{
	if (ino != 2)
		fuse_reply_err(req, EISDIR);
	else if ((fi->flags & 3) != O_RDONLY)
		fuse_reply_err(req, EACCES);
	else
		fuse_reply_open(req, fi);
}

static void hello_ll_read(fuse_req_t req, fuse_ino_t ino, size_t size,
			  off_t off, struct fuse_file_info *fi)
{
	(void) fi;

	assert(ino == 2);
	reply_buf_limited(req, hello_str, strlen(hello_str), off, size);
}

static struct fuse_lowlevel_ops hello_ll_oper = {
	.lookup		= hello_ll_lookup,
	.getattr	= hello_ll_getattr,
	.readdir	= hello_ll_readdir,
	.open		= hello_ll_open,
	.read		= hello_ll_read,
};

struct se_ch {
    struct fuse_chan * ch;
    struct fuse_session * se;
    size_t bufsize;
    char * buf;
    char * mountpoint;
};

static struct se_ch se_ch_loop = {
    .ch = NULL,
    .se = NULL,
    .bufsize = 0,
    .buf = NULL,
};

/* Returns the fd */
int fuse_session_loop_begin(struct fuse_session *se)
{
	struct fuse_chan *ch = fuse_session_next_chan(se, NULL);
	size_t bufsize = fuse_chan_bufsize(ch);
	char *buf = (char *) malloc(bufsize);
	if (!buf) {
		fprintf(stderr, "fuse: failed to allocate read buffer\n");
		return -1;
	}
  se_ch_loop.ch = ch;
  se_ch_loop.se = se;
  se_ch_loop.bufsize = bufsize;
  se_ch_loop.buf = buf;

  return fuse_chan_fd(se_ch_loop.ch);
}


int fuse_session_loop_middle() {
	int res = 0;
	if (!fuse_session_exited(se_ch_loop.se)) {
		struct fuse_chan *tmpch = se_ch_loop.ch;
		res = fuse_chan_recv(&tmpch, se_ch_loop.buf, se_ch_loop.bufsize);
		if (res == -EINTR)
      return 1;
		if (res <= 0) {
      free(se_ch_loop.buf);
      fuse_session_reset(se_ch_loop.se);
      return 0;
    }
		fuse_session_process(se_ch_loop.se, se_ch_loop.buf, res, tmpch);
    return 1;
	} else {
    free(se_ch_loop.buf);
    fuse_session_reset(se_ch_loop.se);
    return 0;
  }
}


static char *argvv[] = {"./bait", "fuse", 0};
static int argcv = 2;
static char * mount_dir = NULL;


int init_apex_fuse(int argc, char *argv[])
{
	
  const gchar * user_data_dir = g_get_user_data_dir();
  pid_t pid = getpid();
  GString * pid_buf = g_string_new(NULL);
  g_string_printf(pid_buf, "%d", pid);
  mount_dir = g_build_filename(user_data_dir, "apex", pid_buf->str, NULL);
  g_string_free(pid_buf, TRUE);
  g_print("%s\n", mount_dir);
  if (!g_file_test(mount_dir, G_FILE_TEST_EXISTS)) {
    if (g_mkdir_with_parents(mount_dir, 0755) < 0) {
        perror("Couldn't create requested directory");
    }
  }
  argvv[1] = mount_dir;

	struct fuse_args args = FUSE_ARGS_INIT(argcv, argvv);
  g_print("%d %s %s \n", argc, argv[0], argv[1]);
	struct fuse_chan *ch;
	char *mountpoint;
	int fd = -1;

  
/*
  const gchar * home = g_get_home_dir();
  if (NULL == home) {
    perror("$HOME variable not set");
  }
  */
  
	if (fuse_parse_cmdline(&args, &mountpoint, NULL, NULL) != -1 &&
	    (ch = fuse_mount(mountpoint, &args)) != NULL) {
    g_print("FUSE mountpoint = %s", mountpoint);
		struct fuse_session *se;
		se = fuse_lowlevel_new(&args, &hello_ll_oper, sizeof(hello_ll_oper), NULL);
		if (se != NULL) {
			if (fuse_set_signal_handlers(se) != -1) {
				fuse_session_add_chan(se, ch);
        se_ch_loop.mountpoint = mountpoint;
				fd = fuse_session_loop_begin(se);
			}
		}
	}
				
	return fd;
}
				
void finish_apex_fuse() {
  fuse_remove_signal_handlers(se_ch_loop.se);
  fuse_session_remove_chan(se_ch_loop.ch);
  fuse_session_destroy(se_ch_loop.se);
  fuse_unmount(se_ch_loop.mountpoint, se_ch_loop.ch);
  g_rmdir(mount_dir);
  g_free(mount_dir);
}
