#ifndef HAVE_SETXATTR
#define HAVE_SETXATTR 1
#endif

// We must set HAVE_SETXATTR for now, because if it is not set,
// cp to our mountpoint will give an error because it is unable
// to set the attributes

/*
    This is 'dupfs', which causes a copy of any files written to
    the mount point to be duplicated in the directory which is
    mounted over it.  NOT a cow system, but more of a backup
    system (without versioning).  Intended for use as part
    of a multi-fs stack to create offsite encrypted backups
    on the fly, suitable for disaster recovery.  Note that
    the copy happens only when all access to the file have
    completed, and the file was opened in a write mode.

    Based on fusexmp code from FUSE: Filesystem in Userspace
    Copyright (C) 2001-2007  Miklos Szeredi <miklos@szeredi.hu>
    and using the build structure and main() taken from a
    slightly different 'dupfs' by kim@kulak.ca (which is really
    just a loopback mount, like mount -bind ..., found at
    http://osdir.com/ml/file-systems.fuse.devel/2005-02/msg00011.html )

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

    gcc -Wall `pkg-config fuse --cflags --libs` dupfs.c -o dupfs

 */


/*

To do this trick, we have to be able to write through the mountpoint
to the underlying directory... normally having mounted anything on
top of a directory, the underlying directory becomes inaccessible.

From the FAQ:

  If a filesystem is mounted over a directory, how can I access
  the old contents?

 There are two possibilities:

 The first is to use 'mount --bind DIR TMPDIR' to create a copy
 of the namespace under DIR. After mounting the FUSE filesystem
 over DIR, files can still be accessed through TMPDIR. This needs
 root privileges.

 The second is to set the working directory to DIR after mounting
 the FUSE filesystem. For example before fuse_main() do

 save_dir = open(DIR, O_RDONLY);

 And from the init() method do

 fchdir(save_dir); close(save_dir);

 Then access the files with relative paths (with newer LIBC versions
 the *at() functions may also be used instead of changing the CWD).

 This method doesn't need root privileges, but only works on Linux
 (FreeBSD does path resolving in a different way), and it's not even
 guaranteed to work on future Linux versions.

-- so, we're using the second method, and are consciously
sacrificing FreeBSD compatibility.

*/

#define FUSE_USE_VERSION 26

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef linux
/* For pread()/pwrite() */
#define _XOPEN_SOURCE 500
#endif

#include <fuse.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <sys/time.h>
#ifdef HAVE_SETXATTR
#include <sys/xattr.h>
#endif
#include <sys/statfs.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>


//#include "debugf.c"
void debugf(const char *s, ...);

int suppress_debug = (0!=0);
int checked = 0;

#ifndef LOGFILE
#define LOGFILE "/tmp/fusexmp.log"
#endif

#define MAX_STRING 400

char debugline[MAX_STRING];
void debugf(const char *s, ...)
{
  /* OK, I'm going to nail this damn bug for once and all... */
  /* Time to size the string by vfprint'ing it to /dev/null... */
  FILE *errfile;
  static char buff[MAX_STRING*2];
  va_list ap;          
  

  if (checked == 0) {
    checked = 1;
    errfile = fopen(LOGFILE, "r");
    if (errfile == NULL) {
      /* Only want to log if file exists already... */
      suppress_debug = (0==0);
    } else {
      fclose(errfile);
    }
  }

  va_start(ap, s);
  
  {
    FILE *nullfile;
    int string_length;
    
    nullfile = fopen("/dev/null", "w");
    if (nullfile == NULL) {
      errfile = fopen(LOGFILE, "a");
      if (errfile != NULL) {
        fprintf(errfile, "Major error - cannot open /dev/null\n");
        fflush(errfile);
        fclose(errfile);
      }
      exit(1);
    }
    string_length = vfprintf(nullfile, s, ap);
    fclose(nullfile);
    if (string_length < MAX_STRING-2) {
      vsprintf(buff, s, ap);
    } else {
      sprintf(buff, "[%d char debugf string excised]\n", string_length);
    }
  }
  va_end(ap);
  strcpy(debugline, buff);
  
  /* Suppress logging to file, but still allow in window if present */
  
  if (suppress_debug) {
    return;
  }

  fprintf(stderr, "%s", buff);
  errfile = fopen(LOGFILE, "a");
  if (errfile != NULL) {
    fprintf(errfile, "%s", buff);
    fflush(errfile);
    fclose(errfile);
  }

}

/*
 * Filepath of the directory to duplicate. This is initialized before
 * calling fuse_main() and is read-only once initialized.
 */

static char cwd[FILENAME_MAX];
static char initial_working_dir[FILENAME_MAX+1] = { '\0' };
static char cached_mountpoint[FILENAME_MAX+1] = { '\0' };
static int save_dir;
static char *backup_dir = "/tmp";

#ifdef NEVER
/* fullName
 * Concatinate the given directory with the file name to get the name of
 * the file to duplicate in the FUSE filesystem.
 */
static char *fullName(char *buf,const char *path){
    (void)strcpy(buf,cwd);
    (void)strcat(buf,path);
    return(buf);
}
#endif

const char *relative_filename(const char *path) /* add mountpoint to path */
{

  // PROBLEMS:
  //   1) HEAP LEAKAGE
  //   2) <fixed>
  //   3) canonicalising the path (removing .. etc) - there's
  //      a call for it if I can just remember the name.
  //   4) what to do if malloc returns NULL - should we also 'umount'?

  char *ep, *buff;

  buff = strdup(path+1); if (buff == NULL) exit(EXIT_FAILURE);

  ep = buff + strlen(buff) - 1; if (*ep == '/') *ep = '\0'; /* don't think this ever happens except for "/" */

  if (*buff == '\0') strcpy(buff, "."); /* which also needs this */

  return buff;
}
#ifdef NEVER
// neater code?- pinched from http://www.ussg.iu.edu/hypermail/linux/kernel/0508.2/1516.html
/* 
* remove the absolute path part
*/
static char *local=".";
static inline const char *relative_filename(const char *path)
{
  if(strcmp(path,"/")==0)
    return local;
  else
    return (path+1);
}
#endif


static int dup_getattr(const char *path, struct stat *stbuf)
{
    int res;

path = relative_filename(path);
debugf("dupfs: getattr(%s)\n", path);
    res = lstat(path, stbuf);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_access(const char *path, int mask)
{
    int res;

path = relative_filename(path);
debugf("dupfs: access(%s)\n", path);
    res = access(path, mask);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_readlink(const char *path, char *buf, size_t size)
{
    int res;

path = relative_filename(path);
debugf("dupfs: readlink(%s)\n", path);
    res = readlink(path, buf, size - 1);
    if (res == -1)
        return -errno;

    buf[res] = '\0';
    return 0;
}


static int dup_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
                       off_t offset, struct fuse_file_info *fi)
{
    DIR *dp;
    struct dirent *de;

    (void) offset;
    (void) fi;

path = relative_filename(path);
debugf("dupfs: readdir(%s)\n", path);
    dp = opendir(path);
    if (dp == NULL)
        return -errno;

    while ((de = readdir(dp)) != NULL) {
        struct stat st;
        memset(&st, 0, sizeof(st));
        st.st_ino = de->d_ino;
        st.st_mode = de->d_type << 12;
        if (filler(buf, de->d_name, &st, 0))
            break;
    }

    closedir(dp);
    return 0;
}

static int dup_mknod(const char *path, mode_t mode, dev_t rdev)
{
    int res;

    /* On Linux this could just be 'mknod(path, mode, rdev)' but this
       is more portable */
path = relative_filename(path);
debugf("dupfs: mknod(%s)\n", path);
    if (S_ISREG(mode)) {
        res = open(path, O_CREAT | O_EXCL | O_WRONLY, mode);
        if (res >= 0)
            res = close(res);
    } else if (S_ISFIFO(mode))
        res = mkfifo(path, mode);
    else
        res = mknod(path, mode, rdev);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_mkdir(const char *path, mode_t mode)
{
    int res;

path = relative_filename(path);
debugf("dupfs: mkdir(%s)\n", path);
    res = mkdir(path, mode);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_unlink(const char *path)
{
    int res;

path = relative_filename(path);
debugf("dupfs: unlink(%s)\n", path);
    res = unlink(path);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_rmdir(const char *path)
{
    int res;

path = relative_filename(path);
debugf("dupfs: rmdir(%s)\n", path);
    res = rmdir(path);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_symlink(const char *from, const char *to)
{
    int res;

from = relative_filename(from);
to = relative_filename(to);
debugf("dupfs: symlink(%s, %s)\n", from, to);
    res = symlink(from, to);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_rename(const char *from, const char *to)
{
    int res;

from = relative_filename(from);
to = relative_filename(to);
debugf("dupfs: rename(%s, %s)\n", from, to);
    res = rename(from, to);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_link(const char *from, const char *to)
{
    int res;

from = relative_filename(from);
to = relative_filename(to);
debugf("dupfs: link(%s, %s)\n", from, to);
    res = link(from, to);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_chmod(const char *path, mode_t mode)
{
    int res;

path = relative_filename(path);
debugf("dupfs: chmod(%s)\n", path);
    res = chmod(path, mode);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_chown(const char *path, uid_t uid, gid_t gid)
{
    int res;

path = relative_filename(path);
debugf("dupfs: lchown(%s)\n", path);
    res = lchown(path, uid, gid);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_truncate(const char *path, off_t size)
{
    int res;

path = relative_filename(path);
debugf("dupfs: truncate(%s)\n", path);
    res = truncate(path, size);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_utimens(const char *path, const struct timespec ts[2])
{
    int res;
    struct timeval tv[2];

    tv[0].tv_sec = ts[0].tv_sec;
    tv[0].tv_usec = ts[0].tv_nsec / 1000;
    tv[1].tv_sec = ts[1].tv_sec;
    tv[1].tv_usec = ts[1].tv_nsec / 1000;

path = relative_filename(path);
debugf("dupfs: utimes(%s)\n", path);
    res = utimes(path, tv);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_open(const char *path, struct fuse_file_info *fi)
{
    int res;

path = relative_filename(path);
debugf("dupfs: open(%s)\n", path);
    res = open(path, fi->flags);
    if (res == -1)
        return -errno;

    close(res);
    return 0;
}

static int dup_read(const char *path, char *buf, size_t size, off_t offset,
                    struct fuse_file_info *fi)
{
    int fd;
    int res;

    (void) fi;
path = relative_filename(path);
debugf("dupfs: read(%s)\n", path);
    fd = open(path, O_RDONLY);
    if (fd == -1)
        return -errno;

    res = pread(fd, buf, size, offset);
    if (res == -1)
        res = -errno;

    close(fd);
    return res;
}

static int dup_write(const char *path, const char *buf, size_t size,
                     off_t offset, struct fuse_file_info *fi)
{

// actually we don't need to look at the 'open' calls - when
// we call 'write', flag the file's private data with the
// fact that the file was updated, so that we can take a
// copy when we get the 'release' call.

    int fd;
    int res;

    (void) fi;
path = relative_filename(path);
debugf("dupfs: write(%s)\n", path);
    fd = open(path, O_WRONLY);
    if (fd == -1)
        return -errno;

    res = pwrite(fd, buf, size, offset);
    if (res == -1)
        res = -errno;

    close(fd);
    return res;
}

static int dup_statfs(const char *path, struct statvfs *stbuf)
{
    int res;

path = relative_filename(path);
debugf("dupfs: statvfs(%s)\n", path);
    res = statvfs(path, stbuf);
    if (res == -1)
        return -errno;

    return 0;
}

static int dup_release(const char *path, struct fuse_file_info *fi)
{
char *fullpath, *rpath;
// Release is called when there are no more open handles.  This is where
// we do whatever action we want to with the file as all updates are
// now complete.  For example, calling gpg to encrypt it, or rsync
// to transfer it to disaster-recovery storage

// OR look at fi->flags for write access, and assume if opened
// for write, it will have been written to

    fullpath = strdup(path); rpath = relative_filename(fullpath); // assignment discards qualifiers from pointer target type
debugf("dupfs: release(%s) flags=%02x\n", rpath, fi->flags);
    if ((fi->flags&1) != 0) {
      char *target = malloc(strlen(backup_dir)+1+strlen(rpath)+1), *ptr, *source;
      int rc, status;
      pid_t clone;

      sprintf(target, "%s/%s", backup_dir, rpath);
      ptr = strrchr(target, '/'); *ptr = '\0';
      debugf("dupfs TRIGGER: /bin/mkdir -p %s\n", target);
      if ((clone = fork()) == 0) {
        debugf("dupfs: execl /bin/mkdir -p %s\n", target);
        rc = execl("/bin/mkdir", "mkdir", "-p", target, NULL) /* Shouldn't return */; debugf("dupfs: execl /bin/mkdir failed"); exit(rc);
      } else if (clone == -1) {
        debugf("dupfs: fork /bin/mkdir failed"); exit(0);
      } else {
        wait(&status);
      }
      *ptr = '/';
      source = malloc(strlen(cached_mountpoint)+strlen(fullpath)+1);
      sprintf(source, "%s%s", cached_mountpoint, fullpath);
      debugf("dupfs TRIGGER: /bin/cp -pf %s %s\n", source, target);
      if ((clone = fork()) == 0) {
        debugf("dupfs: execl /bin/cp -pf %s %s\n", source, target);
        rc = execl("/bin/cp", "cp", "-pf", source, target, NULL) /* Shouldn't return */; debugf("dupfs: execl /bin/cp failed"); exit(rc);
      } else if (clone == -1) {
        debugf("dupfs: fork /bin/cp failed"); exit(0);
      } else {
        wait(&status);
      }
    }
    return 0;
}

static int dup_fsync(const char *path, int isdatasync,
                     struct fuse_file_info *fi)
{
    /* Just a stub.  This method is optional and can safely be left
       unimplemented */

path = relative_filename(path);
debugf("dupfs: fsync(%s)\n", path);
    (void) path;
    (void) isdatasync;
    (void) fi;
    return 0;
}

#ifdef HAVE_SETXATTR
/* xattr operations are optional and can safely be left unimplemented */
static int dup_setxattr(const char *path, const char *name, const char *value,
                        size_t size, int flags)
{
    int res;
path = relative_filename(path);
debugf("dupfs: setxattr(%s)\n", path);
    res = lsetxattr(path, name, value, size, flags);
    if (res == -1)
        return -errno;
    return 0;
}

static int dup_getxattr(const char *path, const char *name, char *value,
                    size_t size)
{
    int res;

path = relative_filename(path);
debugf("dupfs: getxattr(%s)\n", path);
    res = lgetxattr(path, name, value, size);
    if (res == -1)
        return -errno;
    return res;
}

static int dup_listxattr(const char *path, char *list, size_t size)
{
    int res;

path = relative_filename(path);
debugf("dupfs: listxattr(%s)\n", path);
    res = llistxattr(path, list, size);
    if (res == -1)
        return -errno;
    return res;
}

static int dup_removexattr(const char *path, const char *name)
{
    int res;

path = relative_filename(path);
debugf("dupfs: removexattr(%s)\n", path);
    res = lremovexattr(path, name);
    if (res == -1)
        return -errno;
    return 0;
}
#endif /* HAVE_SETXATTR */

void *dup_init(struct fuse_conn_info *conn)
{
  debugf("dupfs: init()\n");
  // trick to allow mounting as an overlay - doesn't work on freebsd
  fchdir(save_dir);
  close(save_dir);
  (void)conn;
  return NULL;
}

#ifdef NEVER
// This is where we can put some private context:
/** Extra context that may be needed by some filesystems
 *
 * The uid, gid and pid fields are not filled in case of a writepage
 * operation.
 */
struct fuse_context {
    /** Pointer to the fuse object */
    struct fuse *fuse;

    /** User ID of the calling process */
    uid_t uid;

    /** Group ID of the calling process */
    gid_t gid;

    /** Thread ID of the calling process */
    pid_t pid;

    /** Private filesystem data */
    void *private_data;
};
#endif

static struct fuse_operations dup_oper = {

    /** Get file attributes.
     *
     * Similar to stat().  The 'st_dev' and 'st_blksize' fields are
     * ignored.  The 'st_ino' field is ignored except if the 'use_ino'
     * mount option is given.
     */
    //int (*getattr) (const char *, struct stat *);
    .getattr	= dup_getattr,

    /** Read the target of a symbolic link
     *
     * The buffer should be filled with a null terminated string.  The
     * buffer size argument includes the space for the terminating
     * null character.  If the linkname is too long to fit in the
     * buffer, it should be truncated.  The return value should be 0
     * for success.
     */
    //int (*readlink) (const char *, char *, size_t);
    .readlink	= dup_readlink,

    /* Deprecated, use readdir() instead */
    //int (*getdir) (const char *, fuse_dirh_t, fuse_dirfil_t);
    // NOTIMP

    /** Create a file node
     *
     * This is called for creation of all non-directory, non-symlink
     * nodes.  If the filesystem defines a create() method, then for
     * regular files that will be called instead.
     */
    //int (*mknod) (const char *, mode_t, dev_t);
    .mknod	= dup_mknod,

    /** Create a directory */
    //int (*mkdir) (const char *, mode_t);
    .mkdir	= dup_mkdir,

    /** Remove a file */
    //int (*unlink) (const char *);
    .unlink	= dup_unlink,

    /** Remove a directory */
    //int (*rmdir) (const char *);
    .rmdir	= dup_rmdir,

    /** Create a symbolic link */
    //int (*symlink) (const char *, const char *);
    .symlink	= dup_symlink,

    /** Rename a file */
    //int (*rename) (const char *, const char *);
    .rename	= dup_rename,

    /** Create a hard link to a file */
    //int (*link) (const char *, const char *);
    .link	= dup_link,

    /** Change the permission bits of a file */
    //int (*chmod) (const char *, mode_t);
    .chmod	= dup_chmod,

    /** Change the owner and group of a file */
    //int (*chown) (const char *, uid_t, gid_t);
    .chown	= dup_chown,

    /** Change the size of a file */
    //int (*truncate) (const char *, off_t);
    .truncate	= dup_truncate,

    /** Change the access and/or modification times of a file
     *
     * Deprecated, use utimens() instead.
     */
    //int (*utime) (const char *, struct utimbuf *);
    // NOTIMP

    /** File open operation
     *
     * No creation, or truncation flags (O_CREAT, O_EXCL, O_TRUNC)
     * will be passed to open().  Open should check if the operation
     * is permitted for the given flags.  Optionally open may also
     * return an arbitrary filehandle in the fuse_file_info structure,
     * which will be passed to all file operations.
     *
     * Changed in version 2.2
     */
    //int (*open) (const char *, struct fuse_file_info *);
    .open	= dup_open,

    /** Read data from an open file
     *
     * Read should return exactly the number of bytes requested except
     * on EOF or error, otherwise the rest of the data will be
     * substituted with zeroes.  An exception to this is when the
     * 'direct_io' mount option is specified, in which case the return
     * value of the read system call will reflect the return value of
     * this operation.
     *
     * Changed in version 2.2
     */
    //int (*read) (const char *, char *, size_t, off_t, struct fuse_file_info *);
    .read	= dup_read,

    /** Write data to an open file
     *
     * Write should return exactly the number of bytes requested
     * except on error.  An exception to this is when the 'direct_io'
     * mount option is specified (see read operation).
     *
     * Changed in version 2.2
     */
    //int (*write) (const char *, const char *, size_t, off_t,
    //              struct fuse_file_info *);
    .write	= dup_write,

    /** Get file system statistics
     *
     * The 'f_frsize', 'f_favail', 'f_fsid' and 'f_flag' fields are ignored
     *
     * Replaced 'struct statfs' parameter with 'struct statvfs' in
     * version 2.5
     */
    //int (*statfs) (const char *, struct statvfs *);
    .statfs	= dup_statfs,

    /** Possibly flush cached data
     *
     * BIG NOTE: This is not equivalent to fsync().  It's not a
     * request to sync dirty data.
     *
     * Flush is called on each close() of a file descriptor.  So if a
     * filesystem wants to return write errors in close() and the file
     * has cached dirty data, this is a good place to write back data
     * and return any errors.  Since many applications ignore close()
     * errors this is not always useful.
     *
     * NOTE: The flush() method may be called more than once for each
     * open().  This happens if more than one file descriptor refers
     * to an opened file due to dup(), dup2() or fork() calls.  It is
     * not possible to determine if a flush is final, so each flush
     * should be treated equally.  Multiple write-flush sequences are
     * relatively rare, so this shouldn't be a problem.
     *
     * Filesystems shouldn't assume that flush will always be called
     * after some writes, or that if will be called at all.
     *
     * Changed in version 2.2
     */
    //int (*flush) (const char *, struct fuse_file_info *);
    // NOTIMP

    /** Release an open file
     *
     * Release is called when there are no more references to an open
     * file: all file descriptors are closed and all memory mappings
     * are unmapped.
     *
     * For every open() call there will be exactly one release() call
     * with the same flags and file descriptor.  It is possible to
     * have a file opened more than once, in which case only the last
     * release will mean, that no more reads/writes will happen on the
     * file.  The return value of release is ignored.
     *
     * Changed in version 2.2
     */
    //int (*release) (const char *, struct fuse_file_info *);
    .release	= dup_release,

    /** Synchronize file contents
     *
     * If the datasync parameter is non-zero, then only the user data
     * should be flushed, not the meta data.
     *
     * Changed in version 2.2
     */
    //int (*fsync) (const char *, int, struct fuse_file_info *);
    .fsync	= dup_fsync,

    /** Set extended attributes */
    //int (*setxattr) (const char *, const char *, const char *, size_t, int);
#ifdef HAVE_SETXATTR
    .setxattr	= dup_setxattr,
#endif

    /** Get extended attributes */
    //int (*getxattr) (const char *, const char *, char *, size_t);
#ifdef HAVE_SETXATTR
    .getxattr	= dup_getxattr,
#endif

    /** List extended attributes */
    //int (*listxattr) (const char *, char *, size_t);
#ifdef HAVE_SETXATTR
    .listxattr	= dup_listxattr,
#endif

    /** Remove extended attributes */
    //int (*removexattr) (const char *, const char *);
#ifdef HAVE_SETXATTR
    .removexattr= dup_removexattr,
#endif

    /** Open directory
     *
     * This method should check if the open operation is permitted for
     * this  directory
     *
     * Introduced in version 2.3
     */
    //int (*opendir) (const char *, struct fuse_file_info *);
    // NOTIMP

    /** Read directory
     *
     * This supersedes the old getdir() interface.  New applications
     * should use this.
     *
     * The filesystem may choose between two modes of operation:
     *
     * 1) The readdir implementation ignores the offset parameter, and
     * passes zero to the filler function's offset.  The filler
     * function will not return '1' (unless an error happens), so the
     * whole directory is read in a single readdir operation.  This
     * works just like the old getdir() method.
     *
     * 2) The readdir implementation keeps track of the offsets of the
     * directory entries.  It uses the offset parameter and always
     * passes non-zero offset to the filler function.  When the buffer
     * is full (or an error happens) the filler function will return
     * '1'.
     *
     * Introduced in version 2.3
     */
    //int (*readdir) (const char *, void *, fuse_fill_dir_t, off_t,
    //                struct fuse_file_info *);
    .readdir	= dup_readdir,

    /** Release directory
     *
     * Introduced in version 2.3
     */
    //int (*releasedir) (const char *, struct fuse_file_info *);
    // NOTIMP

    /** Synchronize directory contents
     *
     * If the datasync parameter is non-zero, then only the user data
     * should be flushed, not the meta data
     *
     * Introduced in version 2.3
     */
    //int (*fsyncdir) (const char *, int, struct fuse_file_info *);
    // NOTIMP

    /**
     * Initialize filesystem
     *
     * The return value will passed in the private_data field of
     * fuse_context to all file operations and as a parameter to the
     * destroy() method.
     *
     * Introduced in version 2.3
     * Changed in version 2.6
     */
    //void *(*init) (struct fuse_conn_info *conn);
    .init       = dup_init,

    /**
     * Clean up filesystem
     *
     * Called on filesystem exit.
     *
     * Introduced in version 2.3
     */
    //void (*destroy) (void *);
    // NOTIMP

    /**
     * Check file access permissions
     *
     * This will be called for the access() system call.  If the
     * 'default_permissions' mount option is given, this method is not
     * called.
     *
     * This method is not called under Linux kernel versions 2.4.x
     *
     * Introduced in version 2.5
     */
    //int (*access) (const char *, int);
    .access	= dup_access,

    /**
     * Create and open a file
     *
     * If the file does not exist, first create it with the specified
     * mode, and then open it.
     *
     * If this method is not implemented or under Linux kernel
     * versions earlier than 2.6.15, the mknod() and open() methods
     * will be called instead.
     *
     * Introduced in version 2.5
     */
    //int (*create) (const char *, mode_t, struct fuse_file_info *);
    // NOTIMP

    /**
     * Change the size of an open file
     *
     * This method is called instead of the truncate() method if the
     * truncation was invoked from an ftruncate() system call.
     *
     * If this method is not implemented or under Linux kernel
     * versions earlier than 2.6.15, the truncate() method will be
     * called instead.
     *
     * Introduced in version 2.5
     */
    //int (*ftruncate) (const char *, off_t, struct fuse_file_info *);
    // NOTIMP

    /**
     * Get attributes from an open file
     *
     * This method is called instead of the getattr() method if the
     * file information is available.
     *
     * Currently this is only called after the create() method if that
     * is implemented (see above).  Later it may be called for
     * invocations of fstat() too.
     *
     * Introduced in version 2.5
     */
    //int (*fgetattr) (const char *, struct stat *, struct fuse_file_info *);
    // NOTIMP

    /**
     * Perform POSIX file locking operation
     *
     * The cmd argument will be either F_GETLK, F_SETLK or F_SETLKW.
     *
     * For the meaning of fields in 'struct flock' see the man page
     * for fcntl(2).  The l_whence field will always be set to
     * SEEK_SET.
     *
     * For checking lock ownership, the 'fuse_file_info->owner'
     * argument must be used.
     *
     * For F_GETLK operation, the library will first check currently
     * held locks, and if a conflicting lock is found it will return
     * information without calling this method.  This ensures, that
     * for local locks the l_pid field is correctly filled in.  The
     * results may not be accurate in case of race conditions and in
     * the presence of hard links, but it's unlikly that an
     * application would rely on accurate GETLK results in these
     * cases.  If a conflicting lock is not found, this method will be
     * called, and the filesystem may fill out l_pid by a meaningful
     * value, or it may leave this field zero.
     *
     * For F_SETLK and F_SETLKW the l_pid field will be set to the pid
     * of the process performing the locking operation.
     *
     * Note: if this method is not implemented, the kernel will still
     * allow file locking to work locally.  Hence it is only
     * interesting for network filesystems and similar.
     *
     * Introduced in version 2.6
     */
    //int (*lock) (const char *, struct fuse_file_info *, int cmd,
    //             struct flock *);
    // NOTIMP

    /**
     * Change the access and modification times of a file with
     * nanosecond resolution
     *
     * Introduced in version 2.6
     */
    //int (*utimens) (const char *, const struct timespec tv[2]);
    .utimens	= dup_utimens,

    /**
     * Map block index within file to block index within device
     *
     * Note: This makes sense only for block device backed filesystems
     * mounted with the 'blkdev' option
     *
     * Introduced in version 2.6
     */
    //int (*bmap) (const char *, size_t blocksize, uint64_t *idx);
    // NOTIMP
};


int main(int argc, char *argv[])
{
    // dupfs dir-for-copies mountpoint-working-dir -options

    int new_argc;
    char *new_argv[argc];
    char *pret;
    int i;
    int rc;

    if (FILENAME_MAX < 1024) fprintf(stderr, "Warning: FILENAME_MAX = %d\n", FILENAME_MAX);

    // save current directory in order to access files under the mount
    umask(0);
    getcwd(initial_working_dir, FILENAME_MAX);

debugf("dupfs: cwd=%s\n", initial_working_dir);

    /*
     * Copy the argument list given to the program, except for the
     * name of the directory where the duplicates will be written,
     * for fuse_main().
     */
    new_argv[0] = argv[0];
    new_argv[1] = argv[1];

    /* Resolve the given directory to the full pathname and save it. */
debugf("dupfs: realpath(\"%s\", cwd)\n", argv[2]);
    pret = realpath(argv[2],cwd); // massage filename to remove symlinks, ..'s etc
    if( pret == NULL ){
        perror(argv[2]);
        exit(EXIT_FAILURE);
    }

    /* Copy the rest of the command line parameters. */
    for(i = 3; i < argc; i += 1){
        new_argv[i - 1] = argv[i];
    }
    backup_dir = malloc(strlen(initial_working_dir)+1+strlen(new_argv[1])+1);

    if (*new_argv[1] == '/') { // mount point (working directory) is absolute?
      sprintf(backup_dir, "%s", new_argv[1]);
    } else {                  // or relative?
      sprintf(backup_dir, "%s/%s", initial_working_dir, new_argv[1]);
    }

    {
       char backup_dir_copy[PATH_MAX];
       /* Resolve the given directory to the full pathname and save it. */
debugf("dupfs: realpath(\"%s\", backup_dir_copy)\n", backup_dir);
       pret = realpath(backup_dir, backup_dir_copy); // massage filename to remove symlinks, ..'s etc
       if( pret == NULL ){
           perror(argv[2]);
           exit(EXIT_FAILURE);
       }
       free(backup_dir);
       backup_dir = strdup(backup_dir_copy);
    }

    new_argv[1] = cwd;
    new_argc = argc - 1;

    /*
     * Quick sanity check on the directory.
     */
    {
        int ret;
        struct stat fstats;

        ret = stat(cwd,&fstats);
        if( ret < 0 ){
            perror(cwd);
            exit(EXIT_FAILURE);
        } else if( !S_ISDIR(fstats.st_mode) ){
            fprintf(stderr,"%s: Not a directory.\n",cwd);
            exit(EXIT_FAILURE);
        }
    }

    {
      char full_backup_dirname[PATH_MAX+1], temp[PATH_MAX*2+1];

      if (*argv[1] == '/') { // backup dir path is absolute?
        sprintf(temp, "%s", argv[1]);
      } else {               // or relative?
        sprintf(temp, "%s/%s", initial_working_dir, argv[1]);
      }

      /* Resolve the given directory to the full pathname and save it. */
debugf("dupfs: realpath(\"%s\", full_backup_dirname)\n", temp);
      pret = realpath(temp, full_backup_dirname); // massage filename to remove symlinks, ..'s etc
      if( pret == NULL ){
          perror(argv[2]);
          exit(EXIT_FAILURE);
      }
debugf("%s: anything written to %s\n       will be copied to %s\n       (which is really %s)\n",
       new_argv[0], cwd, argv[1], full_backup_dirname);
      if ((strlen(full_backup_dirname) >= strlen(cwd) && (strncmp(full_backup_dirname, cwd, strlen(cwd)) == 0))) {
         debugf("dupfs: backup directory must not be on or below the mount point\n");
         exit(EXIT_FAILURE);
// NOTE: there is still a circumstance where you can recursively write
// to the backup tree and cause an infinite loop, if the backup is *above*
// the mountpoint rather than below... it happens when the relative path
// down from the backup to the mountpoint is duplicated inside the
// mountpoint itself.

// eg  backup:  /mnt/backup
// mountpoint:  /mnt/backup/home/gtoal
// problem directory: /mnt/backup/home/gtoal/home/gtoal
// ... so creating a file /mnt/backup/home/gtoal/home/gtoal/test.txt will
// cause a copy to be written to /mnt/backup/home/gtoal/test.txt
// and then in turn to /mnt/backup/test.txt

// fortunately this case will terminate, unlike the one which we test
// for above, which would otherwise cause an infinite recursion...

      }
    }
debugf("dupfs: main(%s, %s, %s, %s)\n", new_argv[0], new_argv[1], new_argv[2], new_argv[3]);

   strcpy(cached_mountpoint, cwd);

debugf("dupfs: mountpoint=%s\n", cached_mountpoint);

    save_dir = open(cached_mountpoint, O_RDONLY);

    // WE NEED TO ADD A TEST THAT THE BACKUP DIRECTORY IS NOT WITHIN
    // THE HIERARCHY OF THE MOUNTPOINT.  *** TO-DO ***

    rc = fuse_main(new_argc, new_argv, &dup_oper, NULL);

debugf("dupfs: umount(%s, %s, %s, %s)\n", new_argv[0], new_argv[1], new_argv[2], new_argv[3]);

//    cache_invalidate(initial_working_dir);
    exit(rc); return rc;
}