#!/usr/bin/python

import sys
import os
import string
import getopt

config = { "do_install": True,
           "do_remove": True,
           "configlet": None,
           "firstboot_module_path": "/usr/share/firstboot/modules" }

def remove_links():
    global config

    mod_path = config["firstboot_module_path"]

    if config["configlet"]:
        work_list = [config["configlet"]]
    else:
        work_list = []
        for link in os.listdir(mod_path):
            if not os.path.islink(mod_path + "/" + link):
                continue
            dest = os.readlink(mod_path + "/" + link)
            if string.find(dest, "firstboot.py") != -1:
                work_list.append(link[:-3])

    for item in work_list:
        real_item = None
        if os.path.islink("%s/%s.py" % (mod_path, item)):
            real_item = item + ".py"
        else:
            for link in os.listdir(mod_path):
                if not os.path.islink(mod_path + "/" + link):
                    continue
                if link[:len(item)] == item:
                    real_item = link
                    break
        if real_item:
            os.unlink(mod_path + "/" + real_item)

def install_links():
    global config

    restricted_chars = "-"
    mod_path = config["firstboot_module_path"]

    if config["configlet"]:
        work_list = [config["configlet"]]
    else:
        work_list = []
        for dir in os.listdir("/usr/share/configlets"):
            if dir[0] == ".":
                continue
            if not os.path.isdir("/usr/share/configlets/%s" % (dir,)):
                continue
            if not os.path.exists("/usr/share/configlets/%s/main.py" % (dir,)):
                continue

            work_list.append(dir)

    for item in work_list:
        real_item = ""
        for letter in item:
            if letter in restricted_chars:
                break
            real_item = real_item + letter

        dest_path = "%s/%s.py" % (mod_path, real_item)
        os.symlink("/usr/share/configlet-frontends/firstboot.py", dest_path)

def usage(output_file):
    pass

def parse_args():
    global config

    try:
        (options, args) = getopt.getopt(sys.argv[1:], "h?",
                                        ["install=", "remove=", "reinstall=",
                                         "install-all", "remove-all", "update",
                                         "help"])
    except getopt.GetoptError:
        usage(sys.stderr)
        sys.exit(2)

    for (option, arg) in options:
        if option in ("-?", "-h", "--help"):
            usage(sys.stdout)
            sys.exit(0)

        if option[:9] == "--install":
            config["do_install"] = True
            config["do_remove"] = False
        elif option[:8] == "--remove":
            config["do_install"] = False
            config["do_remove"] = True
        elif option[:11] == "--reinstall" or option == "--update":
            config["do_install"] = True
            config["do_remove"] = True

        if option[-4:] == "-all":
            config["configlet"] = None
        else:
            config["configlet"] = arg

def main():
    global config

    parse_args()

    if not os.path.isdir("/usr/share/firstboot/modules"):
        sys.exit(0)

    if config["do_remove"]:
        remove_links()

    if config["do_install"]:
        install_links()

if __name__ == "__main__":
    main()
