#! /usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk
#import gtk.gdk
#import gtk.glade
#import gobject
#import gnome
#import gettext
import os
import sys

import apt
import apt_pkg
import SoftwareProperties.aptsources
#import apt.cache

import re
import subprocess

INSTALL, UPDATE = range(2)

def run_synaptic(action, packages = []):
    cmd = ["/usr/sbin/synaptic", "--hide-main-window",  "--non-interactive"]
    if action == INSTALL:
      cmd.append("--set-selections")
      cmd.append("--progress-str")
      cmd.append("%s" % _("The updates are being applied."))
      cmd.append("--finish-str")
      cmd.append("%s" %  _("Upgrade is complete"))
      proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
      f = proc.stdin
      for s in packages:
        f.write("%s\tinstall\n" % s)
      f.close()
      proc.wait()
    elif action == UPDATE:
      cmd.append("--update-at-startup")
      subprocess.call(cmd)
    else:
      print "run_synaptic() called with unknown action"
      sys.exit(1)

if __name__ == "__main__":
  if os.geteuid() != 0:
    os.system( "gksudo %s" % sys.argv[0] )
    sys.exit()
  _ = str

  mainarchivere = re.compile( "http://.*archive.ubuntu.com.*" )

  archiveuri = "http://archive.ubuntu.com/ubuntu/"

  sourceslist = SoftwareProperties.aptsources.SourcesList()
  for i in sourceslist:
    if mainarchivere.match( i.uri ):
      archiveuri = i.uri
      print "Found archive URI to be:", i.uri
      break
  
  packages_to_install = []
  def ask_feature( text, packages ):
    dialog = gtk.MessageDialog(message_format=text, 
                               type=gtk.MESSAGE_QUESTION,
                               buttons=gtk.BUTTONS_YES_NO)
    if dialog.run() == gtk.RESPONSE_YES:
      packages_to_install.extend(packages)
    dialog.destroy()
  
  ask_feature( "Do you want playback MP3 support?", ["gstreamer0.10-plugins-ugly"] )
  ask_feature( "Do you want common video codec support (DivX, XVid, AC3, but not DVDs)?", ["gstreamer0.10-plugins-ugly", "gstreamer0.10-ffmpeg"] )
  ask_feature( "Do you want other video codecs (still not DVDs, sorry)?", ["gstreamer0.10-plugins-ugly-multiverse"] )
  ask_feature( """Do you want ZeroConf (AKA Bonjour or Rendezvous) support?
This includes resolving hostnames using mDNS.

WARNING: This does not play nice with NetworkManager.""", ["avahi-discover", "gnome-user-share", "libnss-mdns"] )
  ask_feature( """Do you want NetworkManager?
This provides network interface handing in a dynamic way.
Allowing you to select which wireless network or wired 
network to use. You should add nm-applet to your session
to make this useful (add it in System -> Preferences -> 
Session -> Start Up Programs).

WARNING: This does not play nice with ZeroConf (avahi).""", ["network-manager"] )
  
  packages_to_install = set(packages_to_install)
  if len( packages_to_install ) > 0:
    dialog = gtk.MessageDialog(message_format="""I am going to configure your system to get software
that, although still part of Ubuntu, does not
receive as much testing and attention. Also
some of this software may be illegal in your
contry because of patents.

The following packages will be installed:
%s

Is this alright? (if you click "No", no changes will be made)""" % ("\n".join(packages_to_install)), 
                               type=gtk.MESSAGE_QUESTION,
                               buttons=gtk.BUTTONS_YES_NO)
    if dialog.run() == gtk.RESPONSE_YES:
      dialog.destroy()
      sourceslist.backup()
      sourceslist.add( "deb", archiveuri, "dapper", ["universe", "multiverse"] )
      sourceslist.add( "deb-src", archiveuri, "dapper", ["universe"] )
      sourceslist.save()

      run_synaptic( UPDATE )
      run_synaptic( INSTALL, packages_to_install )

      dialog = gtk.MessageDialog(message_format="""The features you requested are now installed, 
but you may need to reboot to see them.
You can run this script again to add more features, 
but I am not smart enough to remove features.""", buttons=gtk.BUTTONS_OK)
      dialog.run()
    else:
      dialog = gtk.MessageDialog(message_format="""Your system have not been modified. Run this script again later if you like.""", buttons=gtk.BUTTONS_OK )
      dialog.run()
