#!/usr/bin/python
#
# Copyright (c) 2012-2015 Alon Swartz <alon@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
from executil import system, ExecError

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

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

    print >> sys.stderr, "Syntax: %s" % (sys.argv[0])
    print >> sys.stderr, __doc__.strip()
    print >> sys.stderr, "\nBlacklist:\n"
    for script in BLACKLIST:
        print >> sys.stderr, "    %s" % script
    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):
        try:
            env = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            system("%s %s" % (env, cmd))
        except ExecError:
            pass

    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 not fname in BLACKLIST:
                self._exec(fpath)

def main():
    args = sys.argv[1:]
    if args and args[0] in ('-h', '--help'):
        usage()

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

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

    confconsole = '/usr/bin/confconsole'
    if os.path.exists(confconsole) and os.access(confconsole, os.X_OK):
        try:
            system(confconsole, '--usage')
        except ExecError:
            pass

if __name__ == "__main__":
    main()

