/* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
 * vim:expandtab:shiftwidth=8:tabstop=8:
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#include <errno.h>

const char *progname;
const char usage_fmt[] = "Usage: %s <file> <mountpoint>\n";
#define INAME_LEN (PATH_MAX + 1)

#define CHECK_IT(exp, pstr) \
if (!(exp)) { \
    fprintf(stderr, "%s: at %s:%d: ", progname, __FILE__, __LINE__); \
    perror((pstr)); \
    exit(1); \
}

#define CHECK_SNPRINTF(rc, len) \
    CHECK_IT((rc) > 0 && (rc) <= (len), "snprintf() failed")

static char *get_iname(char *fname, const char *mtpt)
{
        char *iname;
        int fd, rc;
        struct stat buf;

        iname = malloc(INAME_LEN);
        CHECK_IT(iname, "malloc() failed");

        fd = open(fname, O_CREAT, 0644);
        if (fd < 0 && errno != EISDIR) {
                fprintf(stderr, "%s:%d: open(%s) failed: %s\n", __FILE__,
                        __LINE__, fname, strerror(errno));
                exit(1);
        }

        if (fd >= 0)
                close(fd);

        rc = stat(fname, &buf);
        if (rc != 0) {
                fprintf(stderr, "%s:%d: stat(%s) failed: %s\n", __FILE__,
                        __LINE__, fname, strerror(errno));
                exit(1);
        }

        rc = snprintf(iname, INAME_LEN,
                      "%s/__iopen__/%lu", mtpt, (unsigned long)buf.st_ino);
        CHECK_SNPRINTF(rc, INAME_LEN);

        return iname;
}

int main(int argc, char *argv[])
{
        char *fname, *mtpt, *iname, *pname;
        struct stat buf;
        int rc;
        int i;

        pname = strdup(argv[0]);
        progname = basename(pname);
	
        if (argc != 3) {
                fprintf(stderr, usage_fmt, progname);
                return 1;
        }

        fname = argv[1];
        mtpt  = argv[2];

        iname = get_iname(fname, mtpt);
        printf("%s:started...\n", argv[0]);
        for (i = 0; i < 10000; i++) {
                rc = stat(fname, &buf);
                if (rc != 0) {
                        fprintf(stderr, "%s:%d: stat(%s) failed: %s\n",
                                __FILE__, __LINE__, fname, strerror(errno));
                        exit(1);
                }

                rc = stat(iname, &buf);
                if (rc != 0) {
                        fprintf(stderr, "%s:%d: stat(%s) failed: %s\n",
                                __FILE__, __LINE__, iname, strerror(errno));
                        exit(1);
                }
        }
        printf("%s:finished...\n", argv[0]);

        return 0;
}