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

import subprocess
import shlex
import time



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, r.stderr


def check_disk():
    disk = "fdisk -l|grep -Ew 'sda|sdb|sdc|sdd|sde|sdf|sdg|sdh'|wc -l"
    ret = runcmd(disk, shell=True)
    d = int(ret[0].replace("\n", ""))
    print(d)
    if d in [4, 8]:
        with open('/opt/collect/check.log', 'w') as log_file:
            log_file.write("YES")

        return True
    else:
        with open('/opt/collect/check.log', 'w') as log_file:
            log_file.write("no_disk")

        return False


def check_memory():
#   memory = "free -m|awk 'NR==2{print $2}'"
    memory = "free -h|awk -F'Gi' 'NR==2{print $1}'|awk '{print $2}'"
    ret = runcmd(memory, shell=True)
    m = int(ret[0].replace("\n", ""))
    print(m)
    if m == 15:
        with open('/opt/collect/check.log', 'w') as log_file:
            log_file.write("YES")
        return True
    else:
        with open('/opt/collect/check.log', 'w') as log_file:
            log_file.write("no_memory")
        return False

if __name__ == '__main__':
    while True:
        if check_disk() and check_memory():
            runcmd("/opt/tool/saturn-gpio-set.sh --sys 2")
        else:
            runcmd("/opt/tool/saturn-gpio-set.sh --sys 1")
        time.sleep(2)