# -*- coding: utf-8 -*-
from gLocale import _
from gTools import cleanexit, gLoadPixmap, pathExists, pathRemove, myExecute
from WidgetConfig import gConfigWindow

from Screens.MessageBox import MessageBox
from Components.config import config, NoSave, ConfigText, getConfigListEntry
from enigma import eConsoleAppContainer


class GeminiPassword(gConfigWindow):
	def __init__(self, session, name=None):
		
		config.bp.passwd = NoSave(ConfigText(default=_("none"), fixed_size=False))
		config.bp.val0 = NoSave(ConfigText(default="", fixed_size=False))
		config.bp.val1 = NoSave(ConfigText(default="", fixed_size=False))
		list=[]
		list.append(getConfigListEntry(_("old password") + ":", config.bp.passwd))
		list.append(getConfigListEntry(_("new password") + ":", config.bp.val0))
		list.append(getConfigListEntry(_("new password") + " (" + _("confirm") + "):", config.bp.val1))
		gConfigWindow.__init__(self, session, name or _("change password"), list=list, icon="icon_user.png")
		
		self.__retText=""
		self.__finished=True
		self.container = eConsoleAppContainer()
		self.container_appClosed_conn = self.container.appClosed.connect(self.__finishedC)
		self.container_dataAvail_conn = self.container.dataAvail.connect(self.__dataAvail)

	def KeyExit(self,val=None):
		if self.__finished:
			self.container.kill()
			self.close()
			cleanexit(__name__)
			
	def __finishedC(self, retval):
		print "__finishedC",retval
		self.__finished=True
		if retval==0:
			self.session.openWithCallback(self.KeyExit, MessageBox, _("Successfully set a new password."), MessageBox.TYPE_INFO, timeout=5)
		elif self.__retText!="":
			self.session.open(MessageBox,self.__retText, MessageBox.TYPE_ERROR)
		
	def __dataAvail(self, text):
		self.__retText += text
		
	def KeyGreen(self):
		oldpass = config.bp.passwd.value
		newpass = config.bp.val0.value
		newpasscon = config.bp.val1.value
		
		if newpass=="" or newpasscon=="" or newpass != newpasscon:
			self.session.open(MessageBox,_("new password") + " " + _("wrong") + "!!!", MessageBox.TYPE_ERROR)
			return
		if pathExists("/usr/sbin/chpasswd")==False:
			self.session.open(MessageBox,_("file not found: ") + "/usr/sbin/chpasswd", MessageBox.TYPE_ERROR)
			return

		if myExecute("/usr/bin/gBackground -f 3 -d '%s' -s '%s'" %(oldpass, newpass))==0:
			self.__finished=False
			cmd = "echo \"root:%s\" | chpasswd" %newpass
			self.container.execute(cmd)
		else:
			self.session.open(MessageBox,_("old password") + " " + _("wrong") + "!!!", MessageBox.TYPE_ERROR)
