/*
 * © Copyright 1996-2012 ECMWF.
 * 
 * This software is licensed under the terms of the Apache Licence Version 2.0
 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
 * In applying this licence, ECMWF does not waive the privileges and immunities 
 * granted to it by virtue of its status as an intergovernmental organisation nor
 * does it submit to any jurisdiction.
 */

#include <stdio.h>
#include <sys/types.h>
#include "mars.h"

#if defined(hpux) || defined(linux)
#include <sys/vfs.h>
#endif

#if defined(__alpha) || defined(__APPLE__)
#include <sys/mount.h>
#endif

#if !defined(hpux) && !defined(__alpha) && !(defined(__APPLE__) && defined(__MACH__))
#include <sys/statfs.h>
#endif


int main( int argc, char ** argv ) {

	struct statfs ss;
	int p;
	int limit=-1;
	char *s = *(argv+1);
	long64 size ;


	if(argc<2 || argc>3){
		fprintf(stderr,"Usage: check_fs path [limit in %%]\n");
		fprintf(stderr,"If limit is given: 0 below limit, else 1\n");
		fprintf(stderr,"If limit is not given: %% of used disk\n");
		fprintf(stderr,"If limit is 0     : MBytes of free space\n");
		exit(1);
	}

	if(argc==3)
		limit=atoi(*(argv+2));


	/* check arguments */

#if defined(hpux) || defined(AIX) || defined(linux) || (defined(__APPLE__) && defined(__MACH__))
	if(statfs( s, &ss ))
#else
	if(statfs( s, &ss, sizeof(struct statfs), 0))
#endif
	{
		perror(s);
		fprintf(stderr,"Error obtaining statfs:'%s'\n",s);
		exit(1);
	}

	if(limit == 0)
	{
		size = (long64)ss.f_bfree*(long64)ss.f_bsize;
		printf("%lld\n", size/1024/1024);
	}
	else {

		p=100-((double)ss.f_bfree / (double)ss.f_blocks * 100.0);

		if( limit > 0 )
			printf("%d\n",(limit >= p) ? 0 : 1);
		else
			printf("%d\n",p);
	}

	exit(0);
}
