#!/usr/bin/env python
# -*- coding: UTF8 -*-

# Outil d'installation automatisé nanokron, version 8.04.1 révision 2
#
#       POUR UBUNTU 8.04 HARDY HERON SEULEMENT
#
# Copyright (c) 2005-2009, Jean-François Fortin Tam ~<nekohayo a gmail.com>~
# 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 3 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, see <http://www.gnu.org/licenses/>.

import os, sys
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
import apt, apt_pkg
import subprocess

SOURCE_LIST_PATH = "/etc/apt/sources.list"
DEBUG_MODE=False #set this variable to True if you need to check that you did not make errors in the package selection before release

print """Outil d'installation semi-automatique de Jeffou
http://ubuntu.ecchi.ca

Les informations de progression seront affichees ici.
"""
class Installateur:
    def __init__(self):
        if not DEBUG_MODE:
            #check that the user is root.
            if os.getuid() != 0:
                #on en profite pour faire un peu de ménage
                os.system("rm -R ~/.local/share/mime/")
                os.system("rm ~/.recently-used.xbel")
                #devenons root
                os.popen('gksu ' + os.getcwd() + '/installateur.py')
                sys.exit(0)
            else:
                self.is_root = True
                self.wTree=gtk.glade.XML("ressources/interface.glade")
                dic= {"appliquer": self.appliquer, "quit": self.quit_app}
                self.wTree.signal_autoconnect(dic)
                self.fenetre=self.wTree.get_widget("window1")

                # get the APT lock
                try:
                    apt_pkg.PkgSystemLock()
                except SystemError:
                    self.fenetre.hide()
                    self.d = gtk.MessageDialog(parent=self.fenetre,
                                          flags=gtk.DIALOG_MODAL,
                                          type=gtk.MESSAGE_ERROR,
                                          buttons=gtk.BUTTONS_CLOSE)
                    self.d.set_markup("""<big><b>Un seul outil de gestion de logiciels peut fonctionner à la fois.</b></big>\n
        Veuillez fermer l'autre application, (par exemple: <i>Synaptic</i>, <i>Aptitude</i> ou <i>Gestionnaire de mises à jour</i>) avant de continuer.\n\nToutefois, si vous êtes <i>absolument certain</i> qu'il n'y a pas d'autre gestionnaire de paquets en cours d'exécution, vous pouvez débloquer APT en exécutant cette commande: <b>gksudo rm /var/lib/dpkg/lock</b>""")
                    self.d.set_title("Essaie pas de m'avoir !")
                    res = self.d.run()
                    self.d.destroy()
                    sys.exit()
        elif DEBUG_MODE:#don't show the UI
            self.wTree=gtk.glade.XML("ressources/interface.glade")
            dic= {"appliquer": self.appliquer, "quit": self.quit_app}
            self.wTree.signal_autoconnect(dic)
            self.fenetre=self.wTree.get_widget("window1")
            self.fenetre.hide()
            self.appliquer()

    def appliquer(self, *args):
        self.trucs_a_installer = ""
        self.paquets_additionnels = ""
        widgets_a_examiner = ["table_basic", "table_multimedia", "table_developpement", "table_creation", "table_internet", "table_jeux"]
        for widget in widgets_a_examiner:
            for checkbox in self.wTree.get_widget(widget):
                if checkbox.get_active() and not DEBUG_MODE:#la checkbox est cochée, on la rajoute donc à la liste
                    self.trucs_a_installer += str(checkbox.get_name()) + " "
                elif DEBUG_MODE:#toutes les cases sont à cocher
                    self.trucs_a_installer += str(checkbox.get_name()) + " "
        self.paquets_additionnels = self.wTree.get_widget("more").get_text()
        
        if self.wTree.get_widget("rewrite_sources").get_active():
            self.rewrite_sources = True
        else: self.rewrite_sources = False


        #destroy the window. It's ugly.
        self.fenetre.iconify()
        self.fenetre.hide()#doesn't work, fixme. Actually, not really a problem. It may be better to keep this window handy to allow the user to QUIT properly.

        if DEBUG_MODE:
            #print "DEBUG MODE DESU"
            os.system(("gnome-terminal --hide-menubar --execute sudo apt-get install --simulate "+self.trucs_a_installer + self.paquets_additionnels))##pour des raisons de débuggage, décommenter cette ligne pour savoir la liste des paquets qui seraient installés, et la copier-coller dans apt-get pour vérifier si elle serait valide.
            #self.unlock_apt()
        elif not DEBUG_MODE:
            if self.rewrite_sources: self.write_sources()
            if self.is_root:#encore un security check
                #os.system("wget http://hendrik.kaju.pri.ee/ubuntu/hendrikkaju.gpg -O- | sudo apt-key add -")#screenlets
                #os.system("wget -q http://snapshots.ekiga.net/cvs/gpgkey/buildd.gpg -O- | sudo apt-key add -")#ekiga CVS
                os.system("wget -q http://fr.packages.medibuntu.org/medibuntu-key.gpg -O- | sudo apt-key add -")#medibuntu
                #os.system("wget -q http://download.virtualbox.org/virtualbox/debian/sun_vbox.asc -O- | sudo apt-key add -")#virtualbox, but this outputs a BADSIG error, leaving commented out.
                #os.system("gpg --keyserver hkp://wwwkeys.eu.pgp.net --recv-keys 483170E9 ; gpg --export -a 483170E9 | sudo apt-key add -")#gandalfn
                #pour que ça soit valide, sa clé doit être 483170E9, pas 0x483170E9!
                self.unlock_apt()
                
                #pour le moment, gnome terminal doit se fermer après l'apt-get update
                #os.system("gconftool-2 --set /apps/gnome-terminal/profiles/Default/exit_action -t \"string\" \"close\"")
                #enlevé: --geometry=500x300 et --geometry=900x500 
                self.commande_a_passer = "gnome-terminal --hide-menubar --execute apt-get update"
                os.system(self.commande_a_passer)
                self.commande_a_passer2= "gnome-terminal --hide-menubar --execute apt-get dist-upgrade -y --force-yes"
                os.system(self.commande_a_passer2)
                #on veut pas que gnome terminal foute le camp après les vraies mises à jour.
                #os.system("gconftool-2 --set /apps/gnome-terminal/profiles/Default/exit_action -t \"string\" \"hold\"")
                self.commande_a_passer3= "gnome-terminal --hide-menubar --execute apt-get install -y --force-yes " + str(self.trucs_a_installer) + str(self.paquets_additionnels)
                os.system(self.commande_a_passer3)
                #FIXME: il n'y a pas de success check

                #inutile SI le terminal reste ouvert, sauf que là j'ai décidé de le fermer automatiquement
                self.confirmation = "zenity --info --title \"Fin de l'installation\" --text \"L'installation est finie, fermez-moi.\""
                os.system(self.confirmation)
            sys.exit(0)

    def write_sources(self):
        try:
            source_list = open(SOURCE_LIST_PATH, "w")
            contenu_des_sources = """#### FICHIER GÉNÉRÉ PAR L'INSTALLATEUR AUTOMATISÉ DE KIDDO ####
#### Téléchargé sur http://ubuntu.ecchi.ca ####
deb http://archive.ubuntu.com/ubuntu/ hardy main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu/ hardy-updates restricted main multiverse universe
#deb http://archive.ubuntu.com/ubuntu/ hardy-proposed restricted main multiverse universe
deb http://security.ubuntu.com/ubuntu hardy-security main restricted universe multiverse

## backports
# deb http://archive.ubuntu.com/ubuntu/ hardy-backports main restricted universe multiverse

# partenaires de Canonical
deb http://archive.canonical.com/ubuntu hardy partner

## Medibuntu; codecs et machins restreints
deb http://fr.packages.medibuntu.org/ hardy free non-free #medibuntu
deb http://ppa.launchpad.net/abiword-stable/ubuntu hardy main #abiword
deb http://ppa.launchpad.net/hanno-stock/ubuntu hardy main #enfuse
deb http://ppa.launchpad.net/bzr/ubuntu hardy main #bazaar
deb http://debian.o-hand.com hardy/ #dates, tasks, contacts
deb http://ppa.launchpad.net/c-korn/ubuntu hardy main #VLC nouvelle génération
deb http://ppa.launchpad.net/freenx-team/ubuntu hardy main #freeNX

## désactivés
#deb http://download.virtualbox.org/virtualbox/debian hardy non-free #virtualbox
#deb http://ppa.launchpad.net/stemp/ubuntu hardy main #midori
"""
            source_list.write(contenu_des_sources)
            source_list.close()
        except(IOError), e:
            print "aaaaaaah impossible d'ecrire!", e
            self.alerte = "zenity --info --title \"Droits d'administration requis\" --text \"Vous n'avez pas les privileges requis pour installer les logiciels. Vous devez executer cet outil en tant que super utilisateur. Ouvrez un terminal dans ce dossier, faites 'sudo -s', entrez votre mot de passe, et faites 'python installateur.py'\""
            os.system(self.alerte)
            #destroy the window. It's ugly.
            self.fenetre.hide()
            self.fenetre.destroy()
            self.quit_app()

    def unlock_apt(self):
        """unlock here to make sure that lock/unlock are always run pair-wise (and don't explode on errors)"""
        try:
            apt_pkg.PkgSystemUnLock()
        except SystemError:
            print "WARNING: trying to unlock a not-locked PkgSystem"
            pass


    def quit_app(self, widget=None):
        try:
            self.unlock_apt()
        except:
            print "impossible de débloquer APT"
        gtk.main_quit()
        sys.exit(0)

if __name__ == "__main__":
    app=Installateur()
    gtk.main()
