#!/usr/bin/env /usr/bin/python3.7

''' Parse the [modinit] section in lirc_options.conf and run it. '''

import configparser
import subprocess
import sys

_HELP = ''' Usage: lircd_setup [lirc_options.conf file] '''

_DEFAULT_FILE = "/etc/lirc/lirc_options.conf"


def run_command(parser, key):
    try:
        code = parser.get('modinit', key)
    except configparser.NoOptionError:
        return
    else:
        cmd = ['/bin/sh', '-c', code]
        try:
             subprocess.check_call(cmd)
        except subprocess.CalledProcessError as err:
            print("Cannot execute: " + ' '.join(cmd))
            print(err)


def main():
    ''' Indeed: the main program. '''
    if len(sys.argv) == 1:
        path = _DEFAULT_FILE
    elif len(sys.argv) == 2:
        path = sys.argv[1]
    else:
        sys.stderr.write(_HELP + '\n')
        sys.exit(1)
    parser = configparser.SafeConfigParser()
    try:
        found = parser.read(path)
    except configparser.Error:
        sys.stderr.write("Cannot parse file " + path)
        sys.exit(1)
    if not parser.has_section("modinit"):
        return
    run_command(parser, 'code')
    for ix in range(1, 11):
        run_command(parser, 'code' + str(ix))


if __name__ == '__main__':
    main()


# vim: set expandtab ts=4 sw=4:
