#!/usr/bin/env python
# -*- mode: python -*-
#
# Copyright (C) 2005 Red Hat, Inc.
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

# Exit codes from this program:
#
# 0 - Success
#
# 1 - A fatal error occurred, and the user profile may not have been applied completely.
#
# 2 - One or more recoverable errors ocurred while applying the profile.
#
# If you get an exit code of 1 or 2, please report a bug at
# http://bugzilla.gnome.org/enter_bug.cgi?product=sabayon
# and include the ~/sabayon-debug-log-YYYY-MM-DD-HH-MM-SS.txt as an attachment
# in your bug report.


if __name__ == '__main__':
    import os
    import sys
    import optparse
    import shutil

    from sabayon import userprofile
    from sabayon import config
    from sabayon import debuglog
    from sabayon import errors
    from sabayon import util
    from sabayon import systemdb

    def dprint (fmt, *args):
        debuglog.debug_log (False, debuglog.DEBUG_LOG_DOMAIN_SABAYON_APPLY, fmt % args)

    def mprint (fmt, *args):
        debuglog.debug_log (True, debuglog.DEBUG_LOG_DOMAIN_SABAYON_APPLY, fmt % args)

    util.init_gettext ()

    option_parser = optparse.OptionParser (usage="usage: %prog [-s] [--admin-log-config FILE] [--readable-log-config FILE] [<profilename>]")
    option_parser.add_option ("-s",
                              "--sabayon-session", dest="sabayon_session",
                              action="store_true", default=False)
    # FIXME: say that "man sabayon" will give you the
    # syntax for the debug log config file.
    option_parser.add_option ("--admin-log-config", dest="admin_log_config",
                              metavar="FILE",
                              help="File with options for the debug log (readable by the system administrator)")
    option_parser.add_option ("--readable-log-config", dest="readable_log_config",
                              metavar="FILE",
                              help="File with options for the debug log (readable by Sabayon's helper processes)")

    options, args = option_parser.parse_args ()

    try:
        is_sabayon_session = options.sabayon_session
        admin_log_config_filename = options.admin_log_config or ("~/" + config.LOG_CONFIG_FILENAME)

        if options.readable_log_config != None:
            readable_log_config_filename = options.readable_log_config
        else:
            readable_log_config_filename = os.path.join (util.get_home_dir (), config.LOG_CONFIG_FILENAME)

        debuglog.debug_log_load_configuration (readable_log_config_filename)
        util.set_admin_log_config_filename (admin_log_config_filename)
        util.set_readable_log_config_filename (readable_log_config_filename)

        user_name = util.get_user_name ()
        group_membership = util.get_group_membership ()

        #
        # Begin the process of determining WHICH profile to apply.
        # We have 4 possibilities, rated in order of priority (highest first)
        # 1) We've been passed a profile on the command line.  We'll apply
        #    this above all others, as it allows sysadmins to build their own
        #    apply scripts that override the "autodetect" mechanism.
        # 2) We've detected that a profile applies to this user, via the
        #    users.xml database.  User profiles should override group profiles.
        # 3) The user is a member of a group for which there's a profile.
        #    Apply the profile for the group.
        # 4) The user belongs to multiple groups to which there are profiles.
        #    We'll pick the first one we come across. FIXME: is this good
        #    behavior?
        #

        profile_name = None

        num_args = len (args)
        if num_args == 1:
            # We've been passed a profile name
            profile_name = args[0]
        elif num_args == 0:
            # lookup profile name for user
            profile_name = systemdb.get_user_database().get_profile (user_name)
        else:
            sys.stderr.write (_("Please use -h for usage options"))
            sys.exit (util.EXIT_CODE_FATAL)

        # Test for group lookup
        if not profile_name:
            for group_name in group_membership:
                if systemdb.get_group_database().is_sabayon_controlled (group_name):
                    profile_name = systemdb.get_group_database().get_profile (group_name)
                    break

        if not profile_name:
            mprint ("No profile for user '%s' found", user_name)
            sys.stderr.write (_("No profile for user '%s' found\n") % user_name)
            sys.exit (util.EXIT_CODE_NO_USER_PROFILE)

        #
        # We've determined a profile applies to us.  Clean up existing
        # defaults.
        #

        try:
            shutil.rmtree (os.path.join (util.get_home_dir (), ".gconf.xml.defaults"), True)
            shutil.rmtree (os.path.join (util.get_home_dir (), ".gconf.xml.mandatory"), True)
            os.mkdir (os.path.join (util.get_home_dir (), ".gconf.xml.defaults"))
            os.mkdir (os.path.join (util.get_home_dir (), ".gconf.xml.mandatory"))
        except:
            pass

        mprint ("Applying profile '%s' for user '%s'",
                profile_name, util.get_user_name ())

        profile = userprofile.UserProfile (profile_name)
        profile.apply (is_sabayon_session)

        mprint ("Finished applying profile '%s' for user '%s'",
                profile_name, util.get_user_name ())

        if errors.errors_have_recoverable_error ():
            mprint ("There were recoverable errors while applying the profile.")
    except:
        errors.errors_exit_with_fatal_exception (debuglog.DEBUG_LOG_DOMAIN_SABAYON_APPLY,
                                                 util.get_admin_log_config_filename ())

    errors.errors_exit_helper_normally (util.get_admin_log_config_filename ())
