#!/usr/bin/python

import os
import sys
from graphit.client import GraphITWatcher

class Watcher(GraphITWatcher):
	
	__name__ = 'Disk space usage'
	__version__ = '1.0'
	__wid__ = 'disk'
	__author__ = 'Antoine Millet <antoine@inaps.org>'
		
	def init_options(self, op):		
		op.add_option('--type',
			default='avail',
			choices=('avail', 'free'),
			help=('Type of data to submit: '
			'avail (percent of free space, with root reservation), '
			'free (percent of free space). '
			'(default to avail)')
		)
	
	def check_options(self, op, args):
		op.usage = '%prog [options] url {path,}'
		if len(args) < 2:
			op.error('I need at least a path to check')
		self._paths = args[1:]
	
	def run(self):
		for path in self._paths:
			try:
				stats = os.statvfs(path)
			except OSError, e:
				sys.stderr.write('Error while checking: %s\n' % e)
				continue
			
			if self._options.type == 'avail':
				self.submit(
					path, 
					float(stats.f_blocks - stats.f_bavail) / stats.f_blocks,
					unit='%'
				)
			elif self._options.type == 'free':
				self.submit(
					path, 
					float(stats.f_blocks - stats.f_bfree) / stats.f_blocks,
					unit='%'
				)
				
if __name__ == '__main__':
	Watcher()

