#!/usr/bin/python3
import os
import sys
import string
import subprocess

GRUB_FILE_NAME = "/etc/default/grub"

STR_START = "GRUB_CMDLINE_LINUX_DEFAULT"
SPLASH = "splash "
QUIET = "quiet "
GRUB_UPDATE = "update-grub"

def usage():
    # Help screen
    print('Usage: ' + os.path.basename(__file__) + ' <enable/disable/status>')
    return -1

def check_arg():
    if len(sys.argv) - 1 == 0:
        return usage()
    else:
        if sys.argv[1] == "enable":
            return check_and_insert()
        if sys.argv[1] == "disable":
            return check_and_remove()
        if sys.argv[1] == "status":
            return check_and_print()
        return usage()

def check_and_insert():
    if check_state() == 0:
        insert_splash()

def check_and_remove():
    if check_state() == 1:
        remove_splash()

def check_and_print():
    res = check_state()
    if res == 1:
        print("ACTIVATED")
    elif res == 0:
        print("NOT ACTIVATED")
    else:
        print("ERROR")

def check_state():
    with open(GRUB_FILE_NAME) as file:
        for line in file:
            if line.find(STR_START) >= 0:
                if line.find(SPLASH) > 0:
                    return 1
                else:
                    return 0
    return -1

def remove_splash():
    ok = False
    with open(GRUB_FILE_NAME) as file:
        lines = file.readlines()
        for pos in range(len(lines)):
            if lines[pos].find(STR_START) >= 0:
                if lines[pos].find(SPLASH) > 0:
                    lines[pos] = lines[pos].replace(SPLASH, '')
                    ok = True
                    break
    if ok == True:
        with open(GRUB_FILE_NAME, 'w') as file:
            file.writelines(lines)
        subprocess.run(GRUB_UPDATE)

def insert_splash():
    ok = False
    with open(GRUB_FILE_NAME) as file:
        lines = file.readlines()
        for pos in range(len(lines)):
            if lines[pos].find(STR_START) >= 0:
                if lines[pos].find(QUIET) > 0:
                    lines[pos] = lines[pos].replace(QUIET, QUIET+SPLASH)
                    ok = True
                    break
    if ok == True:
        with open(GRUB_FILE_NAME, 'w') as file:
            file.writelines(lines)
        subprocess.run(GRUB_UPDATE)

exit(check_arg())
