#!/usr/bin/python -tt
# -*- coding: UTF-8 -*-
# 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; version 2 only
#
# 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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Copyright 2003, 2004 Peter Backlund
# Copyright 2004 Thorsten Leemhuis
# Copyright 2006 Van Assche Alphonse
# Copyright 2006, 2007 Stewart Adam

import string
import os
import sys

from livnaConfigDisplay.const import *
from livnaConfigDisplay.const import _

import livnaConfigDisplay.ConfigDisplay
from livnaConfigDisplay.GlxConfig import *
from livnaConfigDisplay import Utils
from livnaConfigDisplay.ConfigFile import ConfigFile

class nvidiaConfigDisplay(GlxConfig):
    def __init__(self):
        GlxConfig.__init__(self)
        self.vendor = 'nvidia'
        self.majorVendor = Utils.getMajorVendor()
        if self.vendor != Utils.getVendor():
            print _('The initscript and installed driver vendors do not match!')
            sys.exit(1)
        self.ldconf = LD_CONF_FILE % (self.vendor)
        try:
            self.doAllBackups()
        except livnaConfigDisplayError, (bkupErrMsg):
            print bkupErrMsg
            sys.exit(1)
        self.xconfig, self.xconfigpath = self.loadXconfig()
        self.config = ConfigFile(STATUS_FILE)
        self.TOP_MOD_DIR = self.getModTopDir()

        # finally, run arg checks.
        self.run()


    def enable(self, isAutoConfigure = True):
        # Backup the file before make any change.
        currentDriver = self.getDriver()
        # Already enabled?
        if currentDriver == self.majorVendor:
            print _('Driver already enabled.')
            return
        # nVidia modules
        self.addModulePath("/extensions/nvidia", self.TOP_MOD_DIR)
        # 'remembering' magic's in here.
        self.config.setOldDriver(currentDriver)
        #currentDriver = self.config.getOldDriver()
        self.toggleDriver(currentDriver, self.majorVendor)
        # Disable dri and GLcore modules - these are no 
        self.removeModule("dri")
        self.removeModule("GLcore")
        # Add glx/dbe/extmod modules when modules section exists
        if self.xconfig.modules:
            for module in ["glx", "dbe", "extmod"]:
                if self.onlyHasModule(module):
                    self.removeModule(module)
                    break
                else:
                    self.addModule(module)
        # Problems with Compiz without these.
        self.addOption(self.majorVendor,"AddARGBGLXVisuals", "True")
        #self.addOption(self.majorVendor,"DisableGLXRootClipping", "True")
        Utils.writeXorgConf(self.xconfig, self.xconfigpath)
        # We have to read saved status file to restore the Xorg configuration. 
        self.restoreconf()


    def disable(self, isAutoConfigure = True):
        self.removeModulePath("/extensions/nvidia", self.TOP_MOD_DIR)
        # Check if it's already disabled
        if self.getDriver() != self.majorVendor:
            print _('Driver already disabled.')
            return
        # Backup the file before make any change.
        prevDriver = self.config.getOldDriver()
        if prevDriver == self.majorVendor:
            print _('Will not allow reverting from driver \'%s\' to \'%s\'.') % (self.vendor, self.vendor)
            print _('Using the \'nv\' driver instead.')
            prevDriver = "nv"
            self.config.setOldDriver("nv")
        self.removeOption(self.majorVendor,"AddARGBGLXVisuals")
        self.removeOption(self.majorVendor,"DisableGLXRootClipping")
        self.toggleDriver(self.majorVendor, prevDriver)
        Utils.writeXorgConf(self.xconfig, self.xconfigpath)
        # We have to save the status file so it can be restored later
        self.storeconf()
        # And return to the Fedora default.
        self.enableAiglx()

    def printUsage(self):
        print _("Usage: ") + self.vendor + _("-config-display [ enable|disable ]")

    def run(self):
        # Check number of arguments
        # arg = action
        if len(sys.argv) == 2:
            arg = sys.argv[1]
        else:
            print _('Wrong number of arguments')
            self.printUsage()
            sys.exit(1)
        # Check value of argument
        if arg.lower() != "enable" and arg.lower() != "disable":
            print _('Invalid command: %s') % arg.lower()
            self.printUsage()
            sys.exit(1)
        try:
            if arg == "enable":
                if self.getActive():
                    self.enable()
                else:
                    print _('livna-config-display\'s `active\' state is False - Exiting')
            elif arg == "disable":
                if self.getActive():
                    self.disable()
        except:
            raise # Uncomment me to show the real error
            print MSG_CONF_APPLY_ERROR
            try:
                self.doAllRestores()
                sys.exit(1)
            except livnaConfigDisplayError, (bkupErrMsg):
                #raise # Uncomment me to show the real error
                print MSG_CONF_RESTORE_ERROR + '\n' + MSG_TRACEBACK % (str(errMsg)) + '\n\n' + str(bkupErrMsg)
                sys.exit(1)

app = nvidiaConfigDisplay()
