#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2017, Florent Thiery
'''
Criticality: High
Checks that the server RAID array is fine.
'''
import glob
import subprocess
import sys
import os

GREEN = '\033[92m'
RED = '\033[91m'
DEF = '\033[0m'


def print_red(string):
    print(RED + string + DEF)


def print_green(string):
    print(GREEN + string + DEF)


def check_raid(dev):
    cmd = '/sbin/mdadm -D %s' % dev
    status, output = subprocess.getstatusoutput(cmd)
    if status != 0:
        print_red('The mdadm command on %s failed:' % dev)
    elif 'degraded' in output:
        print_red('The %s RAID partition is degraded:' % dev)
    else:
        print_green('The %s RAID partition is ok.' % dev)
        return True
    print(cmd)
    print(output)
    return False


if os.path.isfile('/proc/mdstat'):
    all_ok = True
    for r in glob.glob('/dev/md*'):
        # ignore /dev/md folder
        if os.path.exists(r) and not os.path.isdir(r):
            all_ok = min(check_raid(r), all_ok)
    if all_ok:
        print_green('Everything fine')
    else:
        print_red('Some array is in bad shape')
        with open('/proc/mdstat', 'r') as fo:
            print(fo.read())
    sys.exit(int(not all_ok))
else:
    print('No software RAID array found, untestable')
    sys.exit(2)