#!/usr/bin/env python

#  PPPOE (c) Nemanja Jovicic 2008 <nemanja.jovicic@hotmail.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 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#

import screenlets

import gtk
import pango
from screenlets.options import StringOption
from os import system
from os import path
import gobject
import commands
from sys import argv
# use gettext for translation
import gettext

_ = screenlets.utils.get_translator(__file__)

def tdoc(obj):
	obj.__doc__ = _(obj.__doc__)
	return obj

@tdoc
class PPPOEScreenlet(screenlets.Screenlet):
	"""Controls PPPOE connection (connect/disconnect)."""
	# default meta-info for Screenlets
	__name__ = 'PPPOE'
	__version__ = '0.3.1'
	__author__ = 'Nemanja Jovicic'
	__desc__ = __doc__

	# internals
	__timeout = None

	# editable options and defaults
	__update_interval = 1 # every second

	mypath = argv[0][:argv[0].find('PPPOEScreenlet.py')].strip()
	dev="ppp0"

	# constructor
	def __init__(self, **keyword_args):
		# call super
		screenlets.Screenlet.__init__(self, width=80, height=80, **keyword_args)
		self.x=250
		self.y=200
		# set theme
		self.theme_name = "default"

		self.add_menuitem("connect", _("Connect"))
		self.add_menuitem("disconnect", _("Disconnect"))
		self.add_menuitem("pass", _("Change password"))
		# add default menu items
		self.add_default_menuitems()

		self.add_options_group(_('Options'), '')
		self.add_option(StringOption(_('Options'), 'dev',str(self.dev),_('PPPOE device'), _('type in your PPPOE device name (e.g. ppp0)'),))	
	
		self.__timeout = gobject.timeout_add(self.__update_interval * 1000, self.update)

	def __setattr__(self, name, value):
		screenlets.Screenlet.__setattr__(self, name, value)
		

	def update(self):
		gobject.idle_add(self.redraw_canvas)
		return True

	def on_draw(self, ctx):
		if self.theme:
			ctx.save()
			ctx.scale(self.scale , self.scale)
			ctx.translate(0, 0)
			self.theme.render(ctx, 'background')
			ctx.restore()
			
			
			ctx.save()
			ctx.scale(self.scale , self.scale)

			if self.connected()== True:
				ctx.translate(5, 5)
				self.theme.render(ctx, 'on')
			else:
				ctx.translate(5, 5)
				self.theme.render(ctx, 'off')
			ctx.restore()					

	def on_draw_shape(self, ctx):
		if self.theme:
			self.on_draw(ctx)
	
	def menuitem_callback(self, widget, id):
		screenlets.Screenlet.menuitem_callback(self, widget, id)
		if id == "connect":
			self.connect()	
		if id == "disconnect":
			self.disconnect()			
		if id == "pass":
			self.show_edit_dialog()
			

	def show_edit_dialog(self):
		# create dialog
		if not path.isfile(self.mypath + 'pass'):
			password="password"
		else:
			f =  open( self.mypath + "pass","r") #// open for for read
			password = f.read()
			f.close()
		dialog = gtk.Dialog(_("Type in your root password:"), self.window)
		dialog.resize(300, 100)
		dialog.add_buttons(gtk.STOCK_OK, gtk.RESPONSE_OK, 
			gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
		entrybox = gtk.Entry()
		entrybox.set_text(str(password))
		dialog.vbox.add(entrybox)
		entrybox.show()	
		# run dialog
		response = dialog.run()
		if response == gtk.RESPONSE_OK:
			password = entrybox.get_text()
			f =  open( self.mypath + "pass","w") 
			f.write(str(password))
			f.close()
		dialog.hide()
		self.update()

	def on_mouse_down(self, event):
		if event.button ==1 :
	   		if event.x > self.scale*8 and event.x < self.scale*67 and event.y > self.scale*8 and event.y < self.scale*67:			
				if self.connected()==True:
					self.disconnect()
				else:
					self.connect()				
				self.update()

	
	def connected(self):
		ip = commands.getoutput("ifconfig "+self.dev)
		ip = ip[:ip.find(" ")]
		#print ip
		if ip==self.dev:
			return True
		else:
			return False
	
	def connect(self):
		if not path.isfile(self.mypath+'pon.sh'):
			#create pon.sh script for turning on PPPOE
			f =  open( self.mypath + "pon.sh","w") 
			f.write(str("#!/bin/sh \nsudo pon dsl-provider < "+self.mypath+"pass"))
			f.close()
			#adding execute permisions to script
			system("chmod +x "+self.mypath+"pon.sh")
		if not path.isfile(self.mypath + 'pass'):
			self.show_edit_dialog()
		system(self.mypath+"pon.sh")

	def disconnect(self):
		if not path.isfile(self.mypath+'poff.sh'):
			#create pon.sh script for turning on PPPOE
			f =  open( self.mypath + "poff.sh","w") 
			f.write(str("#!/bin/sh \nsudo poff -a < "+self.mypath+"pass"))
			f.close()
			#adding execute permisions to script
			system("chmod +x "+self.mypath+"poff.sh")
		if not path.isfile(self.mypath + 'pass'):
			self.show_edit_dialog()
		system(self.mypath+"poff.sh")
	
	
# If the program is run directly or passed as an argument to the python
# interpreter then create a Screenlet instance and show it
if __name__ == "__main__":
	import screenlets.session
	screenlets.session.create_session(PPPOEScreenlet)
