/*
    pi, Thu Aug 23 21:44:46 CEST 2007
    quick hack to get unionfs lower/upper information about a file
    future use: use in find(1) patch
*/


#include <sys/param.h>
#include <stdlib.h>
#include <errno.h>

#include <stdio.h>

#include <sys/types.h>
#include <sys/stat.h>

#include <sys/param.h>
#include <sys/mount.h>
#include <sys/vnode.h>

int main(int argc, char* argv[])
{
    int i=1;
    int res;
    char rp[PATH_MAX];
    char lowerfn[PATH_MAX];
    char *wdp;
    struct stat statp;
    struct stat lowerstatp;
    struct statfs fs;
    struct mount *mp;
    fsid_t fsid;

    for( ; i<argc ; i++ ) {
	printf("i: %d\n",i);
	if ( realpath(argv[i],rp) == NULL ) {
	    perror("realpath");
	    continue;
	}
	res=stat(argv[i],&statp);
	if ( res != 0 ) {
	    perror("stat");
	    exit(1);
	}
	printf("  path: %s ino: %d dev: %d\n",rp,statp.st_ino,statp.st_dev);

	/* wie kommt man an die fsid des filesystems eines files ? statfs(2) */
	res=statfs(argv[i],&fs);
	if ( res != 0 ) {
	    perror("statfs");
	    exit(1);
	}
	printf("   dev: %s\n    to: %s  ",fs.f_mntfromname, fs.f_mntonname );
	printf("fstype: %d ",fs.f_type);
	printf("fstypename: %s\n",fs.f_fstypename);

	if ( strncmp(fs.f_fstypename,"unionfs", 7) != 0 ) {
	    printf("file not on unionfs, skipping: %s\n",rp);
	    continue;
	}
	sprintf(lowerfn,"%s%s",
		fs.f_mntfromname + 8,
		rp+strlen(fs.f_mntonname)
	);

	printf(" found: %s ",lowerfn);

	res=stat(lowerfn,&lowerstatp);
	printf("ino: %d dev: %d\n",lowerstatp.st_ino,lowerstatp.st_dev);

	if ( statp.st_ino != lowerstatp.st_ino ) {
	    printf(" is upper\n");
	}
	else {
	    printf(" is lower\n");
	}

    }

}

