#!/usr/bin/env python3
#
# Copyright (C) 2016  UAVCAN Development Team  <uavcan.org>
#
# This software is distributed under the terms of the MIT License.
#
# Author: Pavel Kirienko <pavel.kirienko@zubax.com>
#

import os
import sys
import multiprocessing

#
# When frozen, stdout/stderr are None, causing nasty exceptions. This workaround silences them.
#
class SupermassiveBlackHole:
    def write(self, *_):
        pass

    def read(self, *_):
        pass

    def flush(self):
        pass

    def close(self):
        pass
try:
    sys.stdout.flush()
    sys.stderr.flush()
except AttributeError:
    sys.__stdout__ = sys.stdout = SupermassiveBlackHole()
    sys.__stderr__ = sys.stderr = SupermassiveBlackHole()
    sys.__stdin__  = sys.stdin  = SupermassiveBlackHole()

#
# This shim enables us to run directly from the source directory not having the package installed.
#
try:
    directory = os.path.dirname(os.path.abspath(__file__))
    if 'gui_tool' in directory:
        print('Running from the source directory')
        for dirpath, dirnames, filenames in os.walk(os.path.join(directory, '..')):
            for d in dirnames:
                if '.' not in d and 'bin' not in d:
                    sys.path.insert(0, os.path.abspath(os.path.join(directory, '..', d)))
            break
        sys.path.insert(0, os.path.abspath(os.path.join(directory, '..')))
except NameError:
    pass                # Seems like we're running in cx_Freeze environment

#
# Calling main directly.
# The 'if' wrapper is absolutely needed because we're spawning new processes with 'multiprocessing'; refer
# to the Python docs for more info.
#
if __name__ == '__main__':
    multiprocessing.freeze_support()
    from dronecan_gui_tool.main import main
    main()
