#!/usr/bin/python3
# -*- coding: utf-8 -*-

import datetime
import subprocess
import shlex

logpath = "/opt/collect/"


def runcmd(cmd, shell=False, encoding='utf-8'):
    args = cmd if shell else shlex.split(cmd)
    r = subprocess.run(args, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding=encoding)
    return r.stdout, r.returncode


def logs(log: str):
    logfile = "mdstat.log"
    with open(logpath + logfile, "a") as f:
        t = str(datetime.datetime.now()).split(".")[0]
        line = t + " " + log + "\n"
        print(line, end="")
        f.write(line)


def check_part():
    cmd = "fdisk -l | grep -c RAID"
    ret = int(runcmd(cmd, shell=True)[0])
    if ret == 4:
        return 4
    elif ret == 8:
        return 8
    else:
        return 0


def md_stat():
    cmd = "cat /proc/mdstat | egrep -o \"md[0-9]{1,3}|: .* raid[0-9]{1,2}|sd[a-z]{1}[0-9]{1}\""
    ret = runcmd(cmd, shell=True)
    if not ret[1]:
        sls = ret[0].split("\n")
        return sls[0:len(sls)-1]
    else:
        return 0


def fix_md(name, stat, disk):
    log = 0
    devs = ""
    disks = sorted(disk)
    for d in disks:
        devs = devs + "/dev/" + d + " "
    if "inactive" in stat:               
        cmd1 = "mdadm -S /dev/{}".format(name)
        cmd2 = f"mdadm -Af /dev/md5 {devs}"
        runcmd(cmd1)
        ret = runcmd(cmd2, shell=True)
        if name == "md127":
            runcmd("mdadm -Ds > /etc/mdadm.conf", shell=True)   
        log = "{}: inactive, repair: {} {}".format(name, ret[1], ret[0])
                                          
    elif "auto-read-only" in stat:       
        cmd1 = "mdadm --readwrite /dev/{}".format(name)
        ret = runcmd(cmd1)
        log = "{}: auto-read-only, repair: {} {}".format(name, ret[1], ret[0])
        if name == "md127":
            runcmd("mdadm -S /dev/md127")
            ret = runcmd(f"mdadm -Af /dev/md5 {devs}", shell=True)  
            runcmd("mdadm -Ds > /etc/mdadm.conf", shell=True)
            log = log + "& md127 rename: {} {}".format(ret[1], ret[0])
        
    elif name == "lost":
        ret = runcmd(f"mdadm -Af /dev/md5 {devs}", shell=True)
        runcmd("mdadm -Ds > /etc/mdadm.conf", shell=True)
        log = "md lost, repair: {} {}".format(ret[1], ret[0])
    
    if log:
        logs(log)


if __name__ == '__main__':
    ds = check_part()
    if ds:
        md = md_stat()
        if md:
            fix_md(md[0], md[1], md[2:])
        else:
            fix_md("lost")

