#!/usr/local/cpython-3.2/bin/python

import os
import sys

sys.path.insert(0, os.path.expanduser('~/lib'))

import mailer as mailer_mod

def main():
    if sys.argv[1:] and sys.argv[1] == '-v':
        verbose = True
    else:
        verbose = False

    bad_us = False

    md0_line = None
    u_line = None
    with open('/proc/mdstat', 'r') as mdstat_file:
        while True:
            line = mdstat_file.readline()
            if not line:
                break

            if verbose:
                print('got line: %s' % line)
                
            if line.startswith('md0 '):
                md0_line = line
                u_line = mdstat_file.readline()
                if verbose:
                    print('got u_line: %s' % u_line)
                if '[UUU]' in u_line:
                    if verbose:
                        print('All is well')
                else:
                    bad_us = True
                    if verbose:
                        print('Badness found')
        if bad_us or md0_line is None or u_line is None:
            if verbose:
                print('about to mail')
            if md0_line is None:
                body = 'Did not even find the md0 line'
            elif u_line is None:
                body = 'Did not find the UUU line'
            else:
                body = 'Got a bad UUU line: %s' % u_line.strip()

            mailer = mailer_mod.Mailer('strombrg@gmail.com')
            if verbose:
                print('mailing: %s' % body)
            mailer.send(from_address = 'strombrg@gmail.com', to_address='strombrg@gmail.com', subject='RAID status', body=body)

    if verbose:
        print('done')

main()