#! /usr/libexec/platform-python -s
# Copyright (c) 2018 - Adjacent Link LLC, Bridgewater, New Jersey
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
#  * Neither the name of Adjacent Link LLC nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# See toplevel COPYING for more information.

from __future__ import absolute_import, division, print_function
import threading
import sys
import re
import time
import logging
import daemon
import daemon.pidfile
import signal
import os
import traceback

from argparse import ArgumentParser

from waveform_resource.service.manager import Manager


# create the top-level parser
argument_parser = ArgumentParser()

argument_parser.add_argument('plugin',
                             type=str,
                             default='',
                             help='full plugin module class name')

argument_parser.add_argument('--config-file',
                            type=str,
                            metavar='FILE',
                            help='plugin config file.')

argument_parser.add_argument('--log-file',
                            type=str,
                            metavar='FILE',
                            help='log file.')

argument_parser.add_argument('--log-level',
                             type=str,
                             metavar='LEVEL',
                             choices=['critical',
                                      'error',
                                      'warning',
                                      'info',
                                      'debug',
                                      'notset'],
                             default='info',
                             help='log level [default: %(default)s].')

argument_parser.add_argument("--pid-file",
                            type=str,
                            default=None,
                            help="write pid file")

argument_parser.add_argument("--daemonize",
                            "-d",
                            action="store_true",
                            dest="daemonize",
                            default=False,
                            help="daemonize application [default: %(default)s]")

ns = argument_parser.parse_args()

args = vars(ns)

shutdown_event = threading.Event()

def shutdown_handler(signum,frame):
    shutdown_event.set()

def do_main():
    logging.basicConfig(filename=args['log_file'],
                        format='%(asctime)s.%(msecs)03d %(levelname)s: %(message)s',
                        datefmt='%H:%M:%S',
                        level=getattr(logging,args['log_level'].upper()))


    # split plugin into module and class
    m = re.match(r'^(.+)\.(.+)$',args['plugin'])

    if m == None:
        print('malformed plugin module class',file=sys.stderr)
        exit(1)

    plugin_module_name,plugin_class_name = m.groups()

    # import the plugin module
    m = __import__(plugin_module_name,
                   fromlist=['*'])

    # get the plugin class
    plugin_class = getattr(m,plugin_class_name)

    logging.info('importing {} from {}'.format(plugin_class_name,
                                               plugin_module_name))

    service = Manager(plugin_class())

    logging.info('initializing service')

    service.initialize(args['config_file'])

    logging.info('starting service')

    try:
        service.start()
    except:
        logging.error(traceback.format_exc())

        logging.info('destroying service on error')

        service.destroy()

        logging.info('exiting on error')

        return

    logging.info('main thread waiting')

    while not shutdown_event.is_set():
        time.sleep(2)

    logging.info('stopping service')

    service.stop()

    logging.info('destroying service')

    service.destroy()

    logging.info('exiting')

pid_file_context = None

if args['pid_file'] != None:
    pid_file_context = daemon.pidfile.PIDLockFile(args['pid_file'])

if args['config_file'] != None:
    args['config_file'] = os.path.realpath(args['config_file'])

if args['log_file'] != None:
    args['log_file'] = os.path.realpath(args['log_file'])

with daemon.DaemonContext(pidfile=pid_file_context,
                          detach_process=args['daemonize'],
                          signal_map={signal.SIGINT:shutdown_handler,
                                      signal.SIGQUIT:shutdown_handler},
                          stdout=None if args['daemonize'] else sys.stdout,
                          stderr=None if args['daemonize'] else sys.stderr):
    try:
        do_main()
    except:
        print(traceback.format_exc())
