#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include "lutil.h"
#include "cspace.h"

#ifndef ULONG_MAX
#define ULONG_MAX 4294967295
#endif

#if defined(HAS_STATFS) | defined(HAS_STATVFS)

#if defined(HAS_STATFS)
#if defined(STATFS_IN_VFS_H)
#include <sys/vfs.h>
#elif defined(STATFS_IN_STATFS_H)
#include <sys/statfs.h>
#elif defined(STATFS_IN_STATVFS_H)
#include <sys/statvfs.h>
#elif defined(STATFS_IN_MOUNT_H)
#include <sys/mount.h>
#else
#error No include for statfs() call defined
#endif
#elif defined(HAS_STATVFS)
#include <sys/statvfs.h>
#endif

int checkspace(dir,fn,factor)
char *dir,*fn;
int factor;
{
	struct stat st;

#ifdef HAS_STATVFS
	struct statvfs sfs;

	if ((stat(fn,&st) != 0) || (statvfs(dir,&sfs) != 0))
#else
	struct statfs sfs;

#ifdef SCO_STYLE_STATFS
	if ((stat(fn,&st) != 0) || (statfs(dir,&sfs,sizeof(sfs),0) != 0))
#else
	if ((stat(fn,&st) != 0) || (statfs(dir,&sfs) != 0))
#endif
#endif
	{
		logerr("$cannot stat \"%s\" or statfs \"%s\", assume enough space",
			S(fn),S(dir));
		return 1;
	}
	if ((((st.st_size/sfs.f_bsize+1)*factor)/100L) > sfs.f_bfree)
	{
		loginf("Only %lu %lu-byte blocks left on device where %s is located",
			sfs.f_bfree,sfs.f_bsize,S(dir));
		return 0;
	}
	return 1;
}

unsigned long freespace(dir)
char *dir;
{
#ifdef HAS_STATVFS
	struct statvfs sfs;

	if (statvfs(dir,&sfs) != 0)
#else
	struct statfs sfs;

#ifdef SCO_STYLE_STATFS
	if (statfs(dir,&sfs,sizeof(sfs),0) != 0)
#else
	if (statfs(dir,&sfs) != 0)
#endif
#endif
	{
		logerr("$cannot statfs \"%s\", assume plenty space",S(dir));
		return ULONG_MAX;
	}

	if (sfs.f_bfree > (ULONG_MAX / sfs.f_bsize))
		return ULONG_MAX;
	else
		return (sfs.f_bsize * sfs.f_bfree);
}

#else /* does not have stat[v]fs */

int checkspace(dir,fn,factor)
char *dir,*fn;
int factor;
{
	return 1; /* Assume space is enough */
}

unsigned long freespace(dir)
char *dir;
{
	return ULONG_MAX; /* assume there is plenty space */
}

#endif
