Skip to content
Snippets Groups Projects
simpleinit.py 1.86 KiB
Newer Older
#!/usr/bin/env python3

import configparser
import shlex
import sys

from eins import Eins


if len(sys.argv) != 2:
    print(f"Usage: {sys.argv[0]} <path_to_config>")
    exit(1)

config = configparser.ConfigParser()
config.read(sys.argv[1])
runlevels = dict()
for section in config.sections():
    command = config[section]
    if 'Runlevel' not in command:
        print(f"Config section '{section}' is missing a 'Runlevel='!")
        continue
    runlevel = int(command['Runlevel'])
    start = []
    stop = []
    if runlevel not in runlevels:
        runlevels[runlevel] = list()
    if 'CmdStart' in command:
Gigadoc 2's avatar
Gigadoc 2 committed
        start = command['CmdStart'].splitlines()
    if 'CmdStop' in command:
Gigadoc 2's avatar
Gigadoc 2 committed
        stop = command['CmdStop'].splitlines()
    runlevels[runlevel].append({ 'name': section, 'start': start, 'stop': stop })

# TODO: persist last seen runlevel
old_level = 0

eins = Eins()

Gigadoc 2's avatar
Gigadoc 2 committed
def emit_cmds(command_strings):
    for command in command_strings:
        if command == "":
            continue
        print(f"Emitting cmd: {command}")
        argv = shlex.split(command)
        eins.emit_cmd(argv[0], *argv[1:])

# This is a silent command, subinitd already describes the same command
@eins.simple_cmd()
Gigadoc 2's avatar
Gigadoc 2 committed
def telinit(new_level):
    global old_level

    print(f"Level {old_level} -> {new_level} observed")
    new_level = int(new_level)
    if new_level > old_level:
        for i in range(old_level+1, new_level+1):
            if i in runlevels:
                for command in runlevels[i]:
                    print(f"Starting {command['name']}")
Gigadoc 2's avatar
Gigadoc 2 committed
                    emit_cmds(command['start'])
    else:
        for i in reversed(range(new_level+1, old_level+1)):
            if i in runlevels:
                for command in runlevels[i]:
                    print(f"Stopping {command['name']}")
Gigadoc 2's avatar
Gigadoc 2 committed
                    emit_cmds(command['stop'])

    old_level = new_level

eins.run()