# Path: elbepack/updated.py
# class UpdateStatus:
# 
#     # pylint: disable=too-many-instance-attributes
# 
#     def __init__(self):
#         self.monitor = None
#         self.observer = None
#         self.soapserver = None
#         self.stop = False
#         self.step = 0
#         self.nosign = False
#         self.verbose = False
#         self.repo_dir = ""
#         self.status_file = '/var/cache/elbe/update_state.txt'
#         with rw_access_file(self.status_file, self) as f:
#             f.write('ready')
#             f.truncate()
# 
#     def write_status(self, msg):
#         with rw_access_file(self.status_file, self) as f:
#             f.seek(0)
#             f.write(msg)
#             f.truncate()
# 
#     def set_progress(self, step, percent=''):
#         self.step = step
#         self.write_status('in_progress\t%d\t%s' % (step, percent))
# 
#     def set_finished(self, result):
#         self.step = 0
#         self.write_status('finished\t%s' % result)
# 
#     def log(self, msg):
#         if not msg.endswith('\n'):
#             msg += '\n'
# 
#         # parse progress of apt from aptprogress output
#         if self.step == 3:
#             msg_a = msg.split()
#             self.set_progress(3, msg_a[0])
# 
#         if self.step:
#             msg = "(" + str(self.step) + "/3) " + msg
#         if self.monitor:
#             try:
#                 self.monitor.service.msg(msg)
#             except BaseException:
#                 print("logging to monitor failed, removing monitor connection")
#                 self.monitor = None
#                 print(msg)
#         try:
#             syslog(msg)
#         except BaseException:
#             print(msg)
#         if self.verbose:
#             print(msg)
# 
# class UpdateService (ServiceBase):
#     def __init__(self):
#         # init self.app, so that pylint knows,
#         # that it exists
#         self.app = None
# 
#     @rpc(_returns=String)
#     def list_snapshots(self):
#         # pylint: disable=no-self-use
#         # use comma separated string because array of strings triggers a bug in
#         # python suds :(
#         snapshots = ""
# 
#         if os.path.isfile("/etc/elbe_base.xml"):
#             snapshots += "base_version,"
# 
#         lists = os.listdir("/etc/apt/sources.list.d")
# 
#         for l in lists:
#             snapshots += l[:len(l) - 5] + ","
# 
#         return snapshots
# 
#     @rpc(String, _returns=String)
#     def apply_snapshot(self, ver):
#         if ver == "base_version":
#             fname = "/etc/elbe_base.xml"
#         else:
#             fname = self.app.status.repo_dir + "/" + ver + "/new.xml"
# 
#         try:
#             apply_update(fname, self.app.status)
#         # pylint: disable=broad-except
#         except Exception as err:
#             print("%s" % str(err))
#             self.app.status.set_finished('error')
#             return "apply snapshot %s failed" % ver
# 
#         self.app.status.set_finished('OK')
#         return "snapshot %s applied" % ver
# 
#     @rpc(String)
#     def register_monitor(self, wsdl_url):
#         self.app.status.monitor = Client(wsdl_url, timeout=cfg['soaptimeout'])
#         self.app.status.log("connection established")
# 
# class UpdateApplication (Application):
#     def __init__(self, *args, **kargs):
#         Application.__init__(self, *args, **kargs)
#         self.status = UpdateStatus()
# 
# Path: elbepack/updated_monitors.py
# class FileMonitor (UpdateMonitor):
# 
#     class EventHandler (pyinotify.ProcessEvent):
#         def __init__(self, status):
#             pyinotify.ProcessEvent.__init__(self)
#             self.status = status
# 
#         def process_IN_CLOSE_WRITE(self, event):
#             handle_update_file(event.pathname, self.status, remove=True)
# 
#     class ObserverThread (threading.Thread):
#         def __init__(self, status, monitor):
#             threading.Thread.__init__(self, name="ObserverThread")
#             self.status = status
#             self.monitor = monitor
# 
#         def run(self):
#             self.status.log("monitoring updated dir")
# 
#             while 1:
#                 if self.monitor.notifier.check_events(timeout=1000):
#                     self.monitor.notifier.read_events()
#                     self.monitor.notifier.process_events()
# 
#                 if self.status.stop:
#                     if self.status.soapserver:
#                         self.status.soapserver.shutdown()
#                     return
# 
#     def __init__(self, status, update_dir):
#         super(FileMonitor, self).__init__(status)
#         self.wm = pyinotify.WatchManager()
#         self.notifier = pyinotify.Notifier(self.wm)
# 
#         # pylint: disable=no-member
#         self.wm.add_watch(update_dir, pyinotify.IN_CLOSE_WRITE,
#                           proc_fun=FileMonitor.EventHandler(self.status))
#         self.observer = FileMonitor.ObserverThread(self.status, self)
# 
#     def start(self):
#         self.observer.start()
# 
#     def stop(self):
#         pass
# 
#     def join(self):
#         self.observer.join()


import os
import signal
import sys
from optparse import OptionParser
from wsgiref.simple_server import make_server
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
from elbepack.updated import UpdateStatus, UpdateService, UpdateApplication
from elbepack.updated_monitors import FileMonitor
    from elbepack.updated_monitors import USBMonitor
# ELBE - Debian Based Embedded Rootfilesystem Builder
# Copyright (c) 2015 Ferdinand Schwenk <ferdinand@ping.lan>
# Copyright (c) 2017 Kurt Kanzenbach <kurt@linutronix.de>
# Copyright (c) 2017 Manuel Traut <manut@linutronix.de>
#
# SPDX-License-Identifier: GPL-3.0-or-later




try:
    usbmonitor_available = True
except ImportError:
    usbmonitor_available = False


def shutdown(_signum, _fname, status):

# Path: elbepack/updated.py
# class UpdateStatus:
# 
#     # pylint: disable=too-many-instance-attributes
# 
#     def __init__(self):
#         self.monitor = None
#         self.observer = None
#         self.soapserver = None
#         self.stop = False
#         self.step = 0
#         self.nosign = False
#         self.verbose = False
#         self.repo_dir = ""
#         self.status_file = '/var/cache/elbe/update_state.txt'
#         with rw_access_file(self.status_file, self) as f:
#             f.write('ready')
#             f.truncate()
# 
#     def write_status(self, msg):
#         with rw_access_file(self.status_file, self) as f:
#             f.seek(0)
#             f.write(msg)
#             f.truncate()
# 
#     def set_progress(self, step, percent=''):
#         self.step = step
#         self.write_status('in_progress\t%d\t%s' % (step, percent))
# 
#     def set_finished(self, result):
#         self.step = 0
#         self.write_status('finished\t%s' % result)
# 
#     def log(self, msg):
#         if not msg.endswith('\n'):
#             msg += '\n'
# 
#         # parse progress of apt from aptprogress output
#         if self.step == 3:
#             msg_a = msg.split()
#             self.set_progress(3, msg_a[0])
# 
#         if self.step:
#             msg = "(" + str(self.step) + "/3) " + msg
#         if self.monitor:
#             try:
#                 self.monitor.service.msg(msg)
#             except BaseException:
#                 print("logging to monitor failed, removing monitor connection")
#                 self.monitor = None
#                 print(msg)
#         try:
#             syslog(msg)
#         except BaseException:
#             print(msg)
#         if self.verbose:
#             print(msg)
# 
# class UpdateService (ServiceBase):
#     def __init__(self):
#         # init self.app, so that pylint knows,
#         # that it exists
#         self.app = None
# 
#     @rpc(_returns=String)
#     def list_snapshots(self):
#         # pylint: disable=no-self-use
#         # use comma separated string because array of strings triggers a bug in
#         # python suds :(
#         snapshots = ""
# 
#         if os.path.isfile("/etc/elbe_base.xml"):
#             snapshots += "base_version,"
# 
#         lists = os.listdir("/etc/apt/sources.list.d")
# 
#         for l in lists:
#             snapshots += l[:len(l) - 5] + ","
# 
#         return snapshots
# 
#     @rpc(String, _returns=String)
#     def apply_snapshot(self, ver):
#         if ver == "base_version":
#             fname = "/etc/elbe_base.xml"
#         else:
#             fname = self.app.status.repo_dir + "/" + ver + "/new.xml"
# 
#         try:
#             apply_update(fname, self.app.status)
#         # pylint: disable=broad-except
#         except Exception as err:
#             print("%s" % str(err))
#             self.app.status.set_finished('error')
#             return "apply snapshot %s failed" % ver
# 
#         self.app.status.set_finished('OK')
#         return "snapshot %s applied" % ver
# 
#     @rpc(String)
#     def register_monitor(self, wsdl_url):
#         self.app.status.monitor = Client(wsdl_url, timeout=cfg['soaptimeout'])
#         self.app.status.log("connection established")
# 
# class UpdateApplication (Application):
#     def __init__(self, *args, **kargs):
#         Application.__init__(self, *args, **kargs)
#         self.status = UpdateStatus()
# 
# Path: elbepack/updated_monitors.py
# class FileMonitor (UpdateMonitor):
# 
#     class EventHandler (pyinotify.ProcessEvent):
#         def __init__(self, status):
#             pyinotify.ProcessEvent.__init__(self)
#             self.status = status
# 
#         def process_IN_CLOSE_WRITE(self, event):
#             handle_update_file(event.pathname, self.status, remove=True)
# 
#     class ObserverThread (threading.Thread):
#         def __init__(self, status, monitor):
#             threading.Thread.__init__(self, name="ObserverThread")
#             self.status = status
#             self.monitor = monitor
# 
#         def run(self):
#             self.status.log("monitoring updated dir")
# 
#             while 1:
#                 if self.monitor.notifier.check_events(timeout=1000):
#                     self.monitor.notifier.read_events()
#                     self.monitor.notifier.process_events()
# 
#                 if self.status.stop:
#                     if self.status.soapserver:
#                         self.status.soapserver.shutdown()
#                     return
# 
#     def __init__(self, status, update_dir):
#         super(FileMonitor, self).__init__(status)
#         self.wm = pyinotify.WatchManager()
#         self.notifier = pyinotify.Notifier(self.wm)
# 
#         # pylint: disable=no-member
#         self.wm.add_watch(update_dir, pyinotify.IN_CLOSE_WRITE,
#                           proc_fun=FileMonitor.EventHandler(self.status))
#         self.observer = FileMonitor.ObserverThread(self.status, self)
# 
#     def start(self):
#         self.observer.start()
# 
#     def stop(self):
#         pass
# 
#     def join(self):
#         self.observer.join()


# Path: elbepack/commands/updated.py
import os
import signal
import sys
from optparse import OptionParser
from wsgiref.simple_server import make_server
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
from elbepack.updated import UpdateStatus, UpdateService, UpdateApplication
from elbepack.updated_monitors import FileMonitor
    from elbepack.updated_monitors import USBMonitor

# ELBE - Debian Based Embedded Rootfilesystem Builder
# Copyright (c) 2015 Ferdinand Schwenk <ferdinand@ping.lan>
# Copyright (c) 2017 Kurt Kanzenbach <kurt@linutronix.de>
# Copyright (c) 2017 Manuel Traut <manut@linutronix.de>
#
# SPDX-License-Identifier: GPL-3.0-or-later




try:
    usbmonitor_available = True
except ImportError:
    usbmonitor_available = False


def shutdown(_signum, _fname, status):

    status.stop = True