import os
import sys
from datetime import datetime
from subprocess import Popen, PIPE


def log(output, flag="INFO", module="None"):
    print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\t{flag.upper():<10}\
         {module:<15} {output}")


def getRootPrivileges():
    if os.geteuid() != 0:
        log("Root required, getting privileges")
        os.execvp('sudo', ['sudo', 'python3'] + sys.argv)


def writeFile(path, text, mode):
    with open(path, mode) as opened_file:
        opened_file.write(text)


def activateModules(*args):
    output, error = Popen(
        ["modprobe", "--all"] + list(args),
        stdout=PIPE,
        stderr=PIPE
    ).communicate()
    if error:
        log(error.decode("utf-8"), flag="DEBUG", module="MODPROBE")


def aptInstall(*requirements):
    if len(requirements) == 0:
        raise RuntimeError

    log("Update", module="APT-GET")
    output, error = Popen(
            ["apt-get", "update", "-y"],
            stdout=PIPE,
            stderr=PIPE
        ).communicate()
    if error:
        log(error.decode("utf-8"), flag="DEBUG", module="APT-GET")

    for requirement in requirements:
        log(f"Install {requirement}", module="APT-GET")
        output, error = Popen(
                ["apt-get", "install", "-y", requirement],
                stdout=PIPE,
                stderr=PIPE
            ).communicate()
        if error:
            log(error.decode("utf-8"), flag="DEBUG", module="APT-GET")

