#!/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 1
    else:
        return 0


def md_stat():
    cmd = "cat /proc/mdstat | grep md"
    return runcmd(cmd, shell=True)


def fix_md(name, stat=None):
    log = 0
    if "inactive" in stat:               
        cmd1 = "mdadm -S /dev/{}".format(name)
        cmd2 = "mdadm -Af /dev/md5 /dev/sd[a-d]1"
        runcmd(cmd1)
        ret = runcmd(cmd2, shell=True)
        if name == "md127":
            runcmd("mdadm -Ds > /rootfs/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("mdadm -Af /dev/md5 /dev/sd[a-d]1", shell=True)  
            runcmd("mdadm -Ds > /rootfs/etc/mdadm.conf", shell=True)
            log = log + "& md127 rename: {} {}".format(ret[1], ret[0])
        
    elif name == "lost":
        ret = runcmd("mdadm -Af /dev/md5 /dev/sd[a-d]1", shell=True)
        runcmd("mdadm -Ds > /rootfs/etc/mdadm.conf", shell=True)
        log = "md lost, repair: {} {}".format(ret[1], ret[0])
    
    if log:
        logs(log)


if __name__ == '__main__':
    if check_part():
        md = md_stat()
        if not int(md[1]):
            dev = md[0].split(":")[0].replace(" ", "")
            fix_md(dev, md[0])
        else:
            fix_md("lost")

