Fixed build error by changing buildrequires from pkgconfig(turbo-jpeg) to libjpeg...
[platform/upstream/hplip.git] / check-plugin.py
1 #!/usr/bin/env 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: Suma Byrappa, Amarnath Chitumalla
21 #
22 #
23
24 __version__ = '1.0'
25 __title__ = 'AutoConfig Utility for Plug-in Installation'
26 __mod__ = 'hp-check-plugin'
27 __doc__ = "Auto config utility for HPLIP supported multifunction Devices for installing proprietary plug-ins."
28
29 # Std Lib
30 import sys
31 import os
32 import os.path
33 import getopt
34 import signal
35 import operator
36 import time
37
38 # Local
39 from base.g import *
40 from base import utils, device, tui, module, pkit
41 from installer import core_install
42
43
44 # Temp values for testing; May not be needed
45 username = ""
46 device_uri = ""
47 printer_name = ""
48 LOG_FILE = "/var/log/hp/hplip_ac.log" 
49 DBUS_SERVICE='com.hplip.StatusService'
50
51 ##### METHODS #####
52
53 # Send dbus event to hpssd on dbus system bus
54 def send_message(device_uri, printer_name, event_code, username, job_id, title, pipe_name=''):
55     log.debug("send_message() entered")
56     args = [device_uri, printer_name, event_code, username, job_id, title, pipe_name]
57     msg = lowlevel.SignalMessage('/', DBUS_SERVICE, 'Event')
58     msg.append(signature='ssisiss', *args)
59
60     SystemBus().send_message(msg)
61     log.debug("send_message() returning")
62
63 # plugin installation
64 def install_Plugin(systray_running_status, run_directly=False):
65     if run_directly:
66         plugin = PLUGIN_REQUIRED 
67         plugin_reason = PLUGIN_REASON_NONE
68         ok, sudo_ok = pkit.run_plugin_command(plugin == PLUGIN_REQUIRED, plugin_reason)
69         if not ok or not sudo_ok:
70             log.error("Failed to install plug-in.")
71     elif systray_running_status:
72         send_message( device_uri,  printer_name, EVENT_AUTO_CONFIGURE, username, 0, "AutoConfig")
73         log.debug("Event EVENT_AUTO_CONFIGURE sent to hp-systray to invoke hp-plugin")
74     else:
75         log.error("Run hp-systray manually and re-plugin printer")
76         #TBD: needs to run hp-plugin in silent mode. or needs to show error UI to user.
77
78      
79 #install Firmware after plugin installation completion.
80 def install_firmware(Plugin_Installation_Completed):
81
82     #timeout check for plugin installation
83     sleep_timeout = 6000        # 10 mins time out
84     while Plugin_Installation_Completed is False and sleep_timeout != 0:
85         time.sleep(0.3) #0.3 sec delay
86         sleep_timeout = sleep_timeout -3
87         
88         ps_plugin,output = utils.Is_Process_Running('hp-plugin')
89         ps_diagnose_plugin,output = utils.Is_Process_Running('hp-diagnose_plugin')
90  
91         if ps_plugin is False and ps_diagnose_plugin is False:            
92             Plugin_Installation_Completed = True
93             if core.check_for_plugin() == PLUGIN_INSTALLED:
94                 break
95             else:
96                 log.error("Failed to download firmware required files. manually run hp-plugin command in terminal fisrt")
97                 sys.exit(1)
98     
99     execmd="hp-firmware"
100     options=""
101     if usb_bus_id is not None and usb_device_id is not None:
102         options += " -y3 %s:%s"%(usb_bus_id, usb_device_id)
103
104     if log_level is 'debug':
105         options += " -g"
106
107     cmd= execmd + options
108     log.info("Starting Firmware installation.")
109     log.debug("Running command : %s " %cmd)
110     Status, out=utils.run(cmd)
111
112 #    if Status == 0:
113 #        log.info("Installed firmware ")
114 #    else:
115 #        log.error("Failed to install firmware = %s" %Status)
116
117
118 #Usage details
119 USAGE = [(__doc__, "", "name", True),
120          ("Usage: %s [MODE] [OPTIONS]" % __mod__, "", "summary", True),
121          utils.USAGE_MODE,
122          utils.USAGE_GUI_MODE,
123          ("Run in interactive mode:", "-i or --interactive (For future use)", "option", False),
124          utils.USAGE_OPTIONS,
125          ("Install Plug-in through HP System Tray:", "-m (Default)", "option", False),
126          ("Install Plug-in through hp-plugin:", "-p", "option", False),
127          ("Download firmware into the device:", "-F", "option", False),
128          ("Download firmware into the known device:", "-f bbb:ddd, where bbb is the USB bus ID and ddd is the USB device ID. The ':' and all leading zeroes must be present", "option", False),
129          utils.USAGE_HELP,
130          utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
131          utils.USAGE_NOTES,
132          ("-m and -p options can't be used together. ","","note",False),
133          ("-f and -F options can't be used together. ","","note",False)
134         ]
135
136
137 def usage(typ='text'):
138     if typ == 'text':
139         utils.log_title(__title__, __version__)
140
141     utils.format_text(USAGE, typ, __title__, __mod__, __version__)
142     sys.exit(0)
143
144 ##### MAIN #####
145
146
147 try:
148     import dbus
149     from dbus import SystemBus, lowlevel
150 except ImportError:
151         log.error("hp-check-plugin Tool requires dBus and python-dbus")
152         sys.exit(1)
153 try:
154     opts, args = getopt.getopt(sys.argv[1:],'l:hHuUmMf:FpPgG',['gui','help', 'help-rest', 'help-man', 'help-desc','logging='])
155
156 except getopt.GetoptError, e:
157         log.error(e.msg)
158         usage()
159         sys.exit(1)
160
161 if os.getenv("HPLIP_DEBUG"):
162         log.set_level('debug')
163
164 log_level = 'info'
165 Systray_Msg_Enabled = False
166 Plugin_option_Enabled = False
167 Firmware_Option_Enabled = False
168 Firmware_GUI_Option_Enabled = False
169 GUI_Mode = True
170 Is_Plugin_Already_Installed = False
171 usb_bus_id=None
172 usb_device_id=None
173
174 for o, a in opts:
175     if o in ('-h','-H', '--help'):
176         usage()
177
178     elif o == '--help-rest':
179         usage('rest')
180
181     elif o == '--help-man':
182         usage('man')
183
184     elif o in ('-u', '-U','--gui'):
185         # currenlty only GUI mode is supported. hence not reading this option
186         GUI_Mode = True
187
188 #    elif o in ('-i', '-I', '--interactive'):
189 #        #this is future use
190 #        GUI_Mode = False 
191
192     elif o == '--help-desc':
193         print __doc__,
194         sys.exit(0)
195
196     elif o in ('-l', '--logging'):
197         log_level = a.lower().strip()
198
199     elif o in('-g', '-G'):
200         log_level = 'debug'
201
202     elif o in ('-m', '-M'):
203         Systray_Msg_Enabled = True
204     
205     elif o in ('-p', '-P'):
206         Plugin_option_Enabled = True
207  
208     elif o== '-F':
209         Firmware_GUI_Option_Enabled = True
210
211     elif o =='-f':
212         usb_bus_id, usb_device_id = a.split(":", 1)
213         Firmware_Option_Enabled = True
214
215 if not log.set_level (log_level):
216     usage()
217
218 LOG_FILE = os.path.normpath(LOG_FILE)
219 log.info(log.bold("Saving output in log file: %s" % LOG_FILE))
220 if os.path.exists(LOG_FILE):
221     os.remove(LOG_FILE)
222
223 log.set_logfile(LOG_FILE)
224 log.set_where(log.LOG_TO_CONSOLE_AND_FILE)
225 cmd="chmod 774 "+LOG_FILE
226 sts,output = utils.run(cmd)
227 if sts != 0:
228     log.warn("Failed to change log file permissions: %s" %output)
229
230 cmd="chgrp lp "+LOG_FILE
231 sts,output = utils.run(cmd)
232 if sts != 0:
233     log.warn("Failed to change log file group permissions: %s" %output)
234
235 log.debug(" hp-check-plugin started")
236
237 if Plugin_option_Enabled and Systray_Msg_Enabled:
238     log.error("Both -m and -p options can't be used together.")
239     usage()
240     sys.exit(1)
241
242 if Firmware_GUI_Option_Enabled and Firmware_Option_Enabled:
243     log.error("Both -f and -F options can't be used together.")
244     usage()
245     sys.exit(1)
246
247 if Firmware_GUI_Option_Enabled:
248     Firmware_Option_Enabled =True       # Firmware_GUI_Option_Enabled is just to check both -f: and -F enabled or not
249
250 if not Plugin_option_Enabled:
251     Systray_Msg_Enabled = True
252
253 # checking whether HP-systray is running or not. Invokes, if systray is not running
254 status,output = utils.Is_Process_Running('hp-systray')
255 if status is False:
256     Systray_Is_Running=False
257     log.info("hp-systray is not running.")
258     if os.getuid() == 0:
259         log.error(" hp-systray must be running.\n Run \'hp-systray &\' in a terminal. ")
260     else:
261         log.info("Starting hp-systray service")
262         child_pid = os.fork()
263         if child_pid == 0:
264             Systray_Is_Running=True
265             status,output =utils.run('hp-systray &', True, None, 1, False)
266             if status is not 0:
267                 log.error("Failed to start \'hp-systray\' service. Manually run \'hp-sysray &\' from terminal as non-root user.")
268                 Systray_Is_Running=False
269             
270             sys.exit()
271         else:
272             Systray_Is_Running=True
273             time.sleep(2)
274 else:
275     Systray_Is_Running=True
276     log.info("hp-systray service is running\n")
277
278 core = core_install.CoreInstall()
279 core.set_plugin_version()
280 plugin_sts = core.check_for_plugin()
281 if plugin_sts == PLUGIN_INSTALLED:
282     log.info("Device Plugin is already installed")
283     Is_Plugin_Already_Installed = True
284 elif plugin_sts == PLUGIN_VERSION_MISMATCH:
285     log.info("HP Device Plug-in version mismatch or some files are corrupted")
286 else:
287     log.info("HP Device Plug-in is not found.")
288
289 if Systray_Msg_Enabled:
290     if not Is_Plugin_Already_Installed:
291         install_Plugin( Systray_Is_Running)
292
293 elif Plugin_option_Enabled:
294     if not Is_Plugin_Already_Installed:
295         install_Plugin (Systray_Is_Running, True)               # needs to run hp-plugin without usig systray
296
297 if Firmware_Option_Enabled:
298     if Is_Plugin_Already_Installed is False:
299         Plugin_Installation_Completed = False
300     else:
301         Plugin_Installation_Completed = True
302
303     install_firmware(Plugin_Installation_Completed)  
304
305 log.info()
306 log.info("Done.")