#!/usr/bin/env python
# *-* encoding: utf-8 *-*

import os
import optparse
import sys  

reload(sys)
sys.setdefaultencoding('utf8')

CHECK = [ 'nobarrier', 'noatime' ]
USAGE = '''Скрипт для проверки базовых опций монтирования.
    {0} -d, --debug       (verbose режим)
    {0} -m, --monrun      (verbose режим)
'''

class MultisetDict(dict):
    def __setitem__(self, key, value):
        try:
            item = self.__getitem__(key)
        except KeyError:
            super(MultisetDict, self).__setitem__(key, [value])
            return

        item.extend([value])
        super(MultisetDict, self).__setitem__(key, item)

    def update(self, *args):
        for key, value in args:
            self[key] = value

def monrun(dict_points):
   if len(dict_points.values()) == 0:
       print '0; OK'
   else:
       print '1; found bad mount points. Use "{0} -d"'.format(os.path.basename(__file__))

def verbose(dict_points):
   if len(dict_points.values()) == 0:
       print 'Ошибок монтирования не найдено.'
   else:
       print 'Найдены ошибки монтирования:'
       for key1 in dict_points:
           print '  => not found attribute {0} in {1}'.format(key1, dict_points[key1])
 
if __name__ == '__main__':

   parser = optparse.OptionParser( usage=USAGE )
   parser.add_option( "-d", "--debug", action="store_true", dest="debug",
                                    help="вывод отладочной информации")
   parser.add_option( "-m", "--monrun", action="store_true", dest="monrun",
                                    help="вывод в формате monrun")
   (opts, args) = parser.parse_args()

   points = MultisetDict()
   with open('/proc/mounts') as f:
       for line in f.readlines():
           if not line.startswith('/dev/'): continue
           device, mount, fs, attr, ck1, ck2  = line.split()
           result = [ (i, '{0} ({1})'.format(mount, os.path.basename(device))) 
                                            for i in CHECK if not attr.count(i) ]
           points.update(*result)

   if opts.debug: verbose(points)
   if opts.monrun: monrun(points)

