#!/usr/local/bin/python3.1

# (c) 2010 Arno Wagner arno@wagner.name
# Distributed under the GPLv2, see http://www.gnu.org/licenses/gpl-2.0.html

# Aim: Runs a consistency check on the md device given
# and checks mismatch count afterwards. 
# Result: Silent on no error, output to stdout in error.
# Intended for cron-job usage.

import fileinput, re, sys, time

device = 'md5' 

# check device exists and is "active"
flag = False
for l in fileinput.input('/proc/mdstat'):
  l.rstrip('\n')
  if re.search('^'+device+'\s\:\s',l):
    flag = True
    break    
if not flag:
  print('ERROR: Specified device '+device+' not found in /proc/mdstat')
  sys.exit(1)
if not re.search('^'+device+'\s\:\sactive\s',l):
  print('ERROR: Device '+device+' not active:')
  print('       '+ l)
  sys.exit(1)
    
# assemble paths for check
action_p   = '/sys/block/'+device+'/md/sync_action'
mismatch_p = '/sys/block/'+device+'/md/mismatch_cnt'

# make sure no mismatches are present
f = open(mismatch_p, 'r')
mism = f.readline()
f.close()
mism = int(mism)
if mism != 0:
   print('ERROR: Device '+device+' has mismatches before check: '+
     repr(mism))
   sys.exit(1)  
   
# start the check
f = open(action_p, 'w')
f.write('check')
f.close

# wait for the check to complete
while(1):
  f = open(action_p, 'r')
  l = f.readline()
  f.close()
  time.sleep(1)
  if l != 'check\n':
    break

# check mismatches
f = open(mismatch_p, 'r')
mism = f.readline()
f.close()
mism = int(mism)
if mism != 0:
   print('ERROR: Device '+device+' has mismatches: '+
     repr(mism))
   sys.exit(1)  
else:
   pass
#   print(' Device '+device+' has no mismatches')


