#!/usr/bin/python
#
# Copyright (c) 2012 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
"""
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)

BLACKLIST = [
    '10randomize-cronapt',
    '10regen-sshkeys',
    '15regen-sslcert',
    '25ec2-userdata',
    '26ec2-resizerootfs',
    '29preseed',
    '40ec2-sshkeys',
    '82tklbam-restore',
    '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):
        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()

    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()

