#!/usr/bin/python3
#
# Copyright (c) 2012-2015 Alon Swartz <alon@turnkeylinux.org>
# Copyright (c) 2016-2019 TurnKey GNU/Linux https://www.turnkeylinux.org
#
# This file is part of InitHooks.
#
# InitHooks is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
"""
Execute firstboot initialization hooks, skipping blacklist

firstboot.d hook execution environment:

    _TURNKEY_INIT=1

"""
import os
import sys

from conffile import ConfFile
import subprocess


def fatal(e):
    print("error: " + str(e), file=sys.stderr)
    sys.exit(1)


def usage(e=None):
    if e:
        print("error: " + str(e), file=sys.stderr)

    print("Syntax: %s [-h|--help] [-c|--full-confconsole]\n" % (sys.argv[0]), file=sys.stderr)
    print(__doc__.strip(), file=sys.stderr)
    print("\nOptions:\n")
    print("  -h|--help             - print this help and exit")
    print("  -c|--full-confconsole - after initialization open full confconsole (default is basic).")
    print("                          If Confconsole not installed, will be ignored.")
    print("\nBlacklist:\n", file=sys.stderr)
    for script in BLACKLIST:
        print("    %s" % script, file=sys.stderr)
    sys.exit(1)


# deprecated: hooks can use _TURNKEY_INIT to detect if they're running under
# turnkey-init
BLACKLIST = ['15regen-sslcert',
             '92etckeeper', ]


class Config(ConfFile):
    CONF_FILE = "/etc/default/inithooks"


class InitHooks:
    def __init__(self):
        self.conf = Config()

    @staticmethod
    def _exec(cmd):
        subprocess.run(['env',
                        'PATH=/usr/local/sbin:/usr/local/bin:'
                        '/usr/sbin:/usr/bin:/sbin:/bin',
                        cmd])

    def execute(self, dname):
        os.environ['_TURNKEY_INIT'] = '1'
        dpath = os.path.join(self.conf.inithooks_path, dname)
        if not os.path.exists(dpath):
            return

        scripts = os.listdir(dpath)
        scripts.sort()
        for fname in scripts:
            fpath = os.path.join(dpath, fname)
            if os.access(fpath, os.X_OK) and fname not in BLACKLIST:
                self._exec(fpath)


def main():
    if os.geteuid() != 0:
        fatal("turnkey-init must be run with root permissions")

    confconsole = '/usr/bin/confconsole'
    if os.path.exists(confconsole) and os.access(confconsole, os.X_OK):
        confconsole = [confconsole, '--usage']
    else:
        # /bin/true ignores args and always returns true
        confconsole = ['/bin/true', '--null']

    args = sys.argv[1:]
    if args:
        for arg in args:
            if arg in ('-h', '--help'):
                usage()
            if arg in ('-c', '--full-confconsole'):
                confconsole = confconsole[:-1]

    inithooks = InitHooks()
    inithooks.execute('firstboot.d')

    subprocess.run(confconsole)


if __name__ == "__main__":
    main()
