#!/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 userdb

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

        if userdb.get_database().is_sabayon_controlled (user_name):
            try:
                shutil.rmtree (os.path.join (util.get_home_dir (), ".gconf.xml.defaults"))
                shutil.rmtree (os.path.join (util.get_home_dir (), ".gconf.xml.mandatory"))
                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

        num_args = len (args)
        if num_args == 0:
            profile_name = userdb.get_database().get_profile (user_name)
            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)
        elif num_args == 1:
            profile_name = args[0]
        else:
            sys.stderr.write (_("Please use -h for usage options"))
            sys.exit (util.EXIT_CODE_FATAL)

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