Tizen 2.1 base
[platform/upstream/hplip.git] / upgrade.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # (c) Copyright 2011-2014 Hewlett-Packard Development Company, L.P.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 #
20 # Author: Amarnath Chitumalla
21 #
22
23 __version__ = '1.0'
24 __title__ = 'HPLIP upgrade latest version'
25 __mod__ = 'hp-upgrade'
26 __doc__ = "HPLIP installer to upgrade to latest version."
27
28 # Std Lib
29 import getopt, os, sys, re, time
30
31 # Local
32 from base.g import *
33 from base import utils, tui, module
34 from installer.core_install import *
35
36
37
38 USAGE = [(__doc__, "", "name", True),
39          ("Usage: %s [OPTIONS]" % __mod__, "", "summary", True),
40          utils.USAGE_SPACE,
41          utils.USAGE_MODE,
42          ("Run in interactive mode:", "-i or --interactive (Default)", "option", False),
43          ("Run in graphical UI mode:", "-u or --gui (future use)", "option", False),
44          utils.USAGE_SPACE,
45          utils.USAGE_OPTIONS,
46          utils.USAGE_HELP,
47          utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
48          ("Check for update and notify:","--notify","option",False),
49          ("Check only available version:","--check","option",False),
50          ("Non-interactive mode:","-n(Without asking permissions)(future use)","option",False),
51          ("Download Path to install from local system:","-p<path>","option", False),
52          ("Download HPLIP package location:","-d<path> (default location /tmp/)","option", False),
53          ("Override existing HPLIP installation even if latest vesrion is installed:","-o","option",False),
54          ("Take options from the file instead of command line:","-f<file> (future use)","option",False)
55         ]
56
57 def usage(typ='text'):
58     if typ == 'text':
59         utils.log_title(__title__, __version__)
60
61     utils.format_text(USAGE, typ, __title__, __mod__, __version__)
62     sys.exit(0)
63
64 def clean_exit(code=0, waitTerminal=True):
65     change_spinner_state(True)
66     mod.unlockInstance()
67     if CHECKING_ONLY is False and NOTIFY is False and waitTerminal is True:
68         uInput = raw_input("\npress enter to quit.")
69     sys.exit(code)
70
71
72 def parse_HPLIP_version(hplip_version_file, pat):
73     ver = "0.0.0"
74     if not os.path.exists(hplip_version_file):
75         return ver
76
77     try:
78         fp= file(hplip_version_file, 'r')
79     except IOError:
80         log.error("Failed to get hplip version since %s file is not found."%hplip_version_file)
81         return ver
82 #    pat = re.compile(r"""HPLIP (.*) Public Release""")
83     data = fp.read()
84     for line in data.splitlines():
85         if pat.search(line):
86             ver = pat.search(line).group(1)
87             break
88     
89     log.debug("Latest HPLIP version = %s." % ver)
90     return ver
91
92
93 log.set_module(__mod__)
94
95 mode = INTERACTIVE_MODE
96 auto = False
97 HPLIP_PATH=None
98 TEMP_PATH="/tmp/"
99 FORCE_INSTALL=False
100 CHECKING_ONLY=False
101 NOTIFY=False
102 HPLIP_SOURCEFORGE_SITE = "http://feed2js.org/feed2js.php?src=http%3A%2F%2Fsourceforge.net%2Fexport%2Frss2_projnews.php%3Fgroup_id%3D149981"
103 HPLIP_WEB_SITE ="http://hplipopensource.com/hplip-web/index.html"
104
105 try:
106     mod = module.Module(__mod__, __title__, __version__, __doc__, USAGE,
107                     (INTERACTIVE_MODE, GUI_MODE),
108                     (UI_TOOLKIT_QT3, UI_TOOLKIT_QT4), True, True)
109
110     opts, device_uri, printer_name, mode, ui_toolkit, loc = \
111                mod.parseStdOpts('hl:gniup:d:of:', ['notify','check','help', 'help-rest', 'help-man', 'help-desc', 'interactive', 'gui', 'lang=','logging=', 'debug'],
112                      handle_device_printer=False)
113
114
115
116     mod.lockInstance()
117 except getopt.GetoptError, e:
118     log.error(e.msg)
119     usage()
120 #    sys.exit(1)
121
122 if os.getenv("HPLIP_DEBUG"):
123     log.set_level('debug')
124
125 for o, a in opts:
126     if o in ('-h', '--help'):
127         usage()
128
129     elif o == '--help-rest':
130         usage('rest')
131
132     elif o == '--help-man':
133         usage('man')
134
135     elif o in ('-q', '--lang'):
136         language = a.lower()
137
138     elif o == '--help-desc':
139         print __doc__,
140         clean_exit(0,False)
141
142     elif o in ('-l', '--logging'):
143         log_level = a.lower().strip()
144         if not log.set_level(log_level):
145             usage()
146
147     elif o in ('-g', '--debug'):
148         log.set_level('debug')
149
150     elif o == '-n':
151         mode = NON_INTERACTIVE_MODE
152         log.info("NON_INTERACTIVE mode is not yet supported.")
153         usage()
154         clean_exit(0,False)
155  
156     elif o == '-p':
157         HPLIP_PATH=a
158
159     elif o == '-d':
160         TEMP_PATH=a
161     
162     elif o == '-o':
163         FORCE_INSTALL = True
164     
165     elif o in ('-u', '--gui'):
166         log.info("GUI is not yet supported.")
167         usage()
168         clean_exit(0, False)
169     elif o == '--check':
170         CHECKING_ONLY = True
171     elif o == '--notify':
172         NOTIFY = True
173     elif o == '-f':
174         log.info("Option from file is not yet supported")
175         usage()
176         clean_exit(0, False)
177
178 if not NOTIFY and not CHECKING_ONLY:
179     mod.quiet= False
180     mod.showTitle()
181
182 log_file = os.path.normpath('/var/log/hp/hp-upgrade.log')
183
184 if os.path.exists(log_file):
185     os.remove(log_file)
186
187 log.set_logfile(log_file)
188 log.set_where(log.LOG_TO_CONSOLE_AND_FILE)
189
190
191 log.debug("Upgrade log saved in: %s" % log.bold(log_file))
192 log.debug("")
193 try:
194     change_spinner_state(False)
195     core =  CoreInstall(MODE_CHECK)
196 #    core.init()
197     if not core.check_network_connection():
198         log.error("Either Internet is not working or Wget is not installed.")
199         clean_exit(0)
200
201     installed_version=sys_conf.get("hplip","version","0.0.0")
202     log.debug("HPLIP previous installed version =%s." %installed_version)
203
204
205
206     HPLIP_latest_ver="0.0.0"
207     # get HPLIP version info from sourceforge
208     pat = re.compile(r"""HPLIP (.*) Public Release""")
209     sts, HPLIP_Ver_file = utils.download_from_network(HPLIP_SOURCEFORGE_SITE)
210     if sts is True:
211         HPLIP_latest_ver = parse_HPLIP_version(HPLIP_Ver_file, pat)
212
213     # get HPLIP version info from hplip site
214     if HPLIP_latest_ver == "0.0.0":     ## if failed to connect the sourceforge site, then check HPLIP site.
215         pat = re.compile(r"""The current version of the HPLIP solution is version (.*)\. \(.*""")
216         sts, HPLIP_Ver_file = utils.download_from_network(HPLIP_WEB_SITE)
217         if sts is True:
218             HPLIP_latest_ver = parse_HPLIP_version(HPLIP_Ver_file, pat)
219
220     if HPLIP_latest_ver == "0.0.0":
221         log.error("Failed to get latest version of HPLIP.")
222         clean_exit(0)
223
224             
225     if CHECKING_ONLY is True:
226         user_conf.set('upgrade','latest_available_version',HPLIP_latest_ver)
227         log.debug("Available HPLIP version =%s."%HPLIP_latest_ver)
228     elif NOTIFY is True:
229         user_conf.set('upgrade','latest_available_version',HPLIP_latest_ver)
230         if not utils.Is_HPLIP_older_version(installed_version, HPLIP_latest_ver):
231             log.debug("Latest version of HPLIP is already installed.")
232         else:
233                   
234             msg = "Latest version of HPLIP-%s is available."%HPLIP_latest_ver
235             if core.is_auto_installer_support():
236                 distro_type= 1
237             else:
238                 distro_type= 2
239
240
241             if ui_toolkit == 'qt3':
242                 if not utils.canEnterGUIMode():
243                     log.error("%s requires GUI support. Is Qt3 Installed?.. Exiting." % __mod__)
244                     clean_exit(1)
245
246                 try:
247                     from qt import *
248                     from ui.upgradeform import UpgradeForm
249                 except ImportError:
250                     log.error("Unable to load Qt3 support. Is it installed? ")
251                     clean_exit(1)
252                     
253
254                 # create the main application object
255                 app = QApplication(sys.argv)
256                 QObject.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
257                 dialog = UpgradeForm(None, "",0,0,distro_type, msg)
258                 dialog.show()
259
260                 log.debug("Starting GUI loop...")
261                 app.exec_loop()
262                     
263
264             else: #qt4
265                 if not utils.canEnterGUIMode4():
266                     log.error("%s requires GUI support . Is Qt4 installed?.. Exiting." % __mod__)
267                     clean_exit(1)
268
269                 try:
270                     from PyQt4.QtGui import QApplication, QMessageBox
271                     from ui4.upgradedialog import UpgradeDialog
272                 except ImportError:
273                     log.error("Unable to load Qt4 support. Is it installed?")
274                     clean_exit(1)
275
276                 app = QApplication(sys.argv)
277                 dialog = UpgradeDialog(None, distro_type, msg)
278             
279             
280                 dialog.show()
281                 log.debug("Starting GUI loop...")
282                 app.exec_()
283                     
284     else:
285         if FORCE_INSTALL is False:
286             if utils.Is_HPLIP_older_version(installed_version, HPLIP_latest_ver):
287                 ok,choice = tui.enter_choice("\nPress 'y' to continue to upgrade HPLIP-%s (y=yes*, n=no):"%HPLIP_latest_ver, ['y','n'],'y')
288                 if not ok or choice == 'n':
289                     clean_exit(0, False)
290             else:
291                 log.info("Latest version of HPLIP is already installed.")
292                 clean_exit(0,False)
293     
294         # check distro information.
295         if not core.is_auto_installer_support():
296             log.info("Please install HPLIP manually as mentioned in 'http://hplipopensource.com/hplip-web/install/manual/index.html' site")
297             clean_exit(0)
298  
299         # check systray is running?
300         status,output = utils.Is_Process_Running('hp-systray')
301         if status is True:
302             ok,choice = tui.enter_choice("\nSome HPLIP applications are running. Press 'y' to close applications or press 'n' to quit upgrade(y=yes*, n=no):",['y','n'],'y')
303             if not ok or choice =='n':
304                 log.info("Manually close HPLIP applications and run hp-upgrade again.")
305                 clean_exit(0, False)
306         
307             try:
308             # dBus
309             #import dbus
310                 from dbus import SystemBus, lowlevel
311             except ImportError:
312                 log.error("Unable to load DBus.")
313                 pass
314             else:
315                 try:
316                     args = ['', '', EVENT_SYSTEMTRAY_EXIT, prop.username, 0, '', '']
317                     msg = lowlevel.SignalMessage('/', 'com.hplip.StatusService', 'Event')
318                     msg.append(signature='ssisiss', *args)
319                     log.debug("Sending close message to hp-systray ...")
320                     SystemBus().send_message(msg)
321                     time.sleep(0.5)
322                 except:
323                     log.error("Failed to send DBus message to hp-systray/hp-toolbox.")
324                     pass
325
326     
327         toolbox_status,output = utils.Is_Process_Running('hp-toolbox')
328 #        systray_status,output = utils.Is_Process_Running('hp-systray')
329         if toolbox_status is True:
330             log.error("Failed to close either HP-Toolbox/HP-Systray. Manually close and run hp-upgrade again.")
331             clean_exit(0)
332
333       
334         if HPLIP_PATH is not None:
335             if os.path.exists(HPLIP_PATH):
336                 download_file = HPLIP_PATH
337             else:
338                 log.error("%s file is not present. Downloading from Net..." %HPLIP_PATH)
339                 HPLIP_PATH = None
340     
341         if HPLIP_PATH is None:
342             url="http://sourceforge.net/projects/hplip/files/hplip/%s/hplip-%s.run/download" %(HPLIP_latest_ver, HPLIP_latest_ver)
343             download_file = None
344             if TEMP_PATH:
345                 download_file = "%s/hplip-%s.run" %(TEMP_PATH,HPLIP_latest_ver)
346             log.info("Downloading hplip-%s.run file..... Please wait. "%HPLIP_latest_ver ) 
347             sts,download_file = utils.download_from_network(url, download_file, True)
348
349             if not os.path.exists(download_file):
350                 log.error("Failed to download %s file."%download_file)
351                 clean_exit()
352     
353         # Installing hplip run.
354         cmd = "sh %s" %(download_file)
355         log.debug("Upgrading  %s and cmd =%s " %(download_file, cmd))
356         os.system(cmd)
357
358     change_spinner_state(True)
359     mod.unlockInstance()
360 #    log.info("HPLIP upgrade is completed")
361 except KeyboardInterrupt:
362     change_spinner_state(True)
363     mod.unlockInstance()
364     log.error("User exit")
365