#
#   Copyright 2018 EPAM Systems
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
"""
Module fore remote debugging python code in docker containers
PYDEVD_HOST and PYDEVD_PORT should be set to valid values
"""
import os
import logging

LOGGER = logging.getLogger(__name__)

try:
    host = os.getenv('PYDEVD_HOST')
    port = os.getenv('PYDEVD_PORT')
    LOGGER.debug('Docker bootup got configuration: host={!r} port={!r}'.format(host, port))

    if host and port:
        import pydevd

        try:
            port = int(port)
        except ValueError as value_error:
            LOGGER.exception('Invalid port value: {}'.format(port), exc_info=value_error)

        pydevd.settrace(
            host=host,
            port=int(port),
            suspend=False,
            patch_multiprocessing=True,
            stdoutToServer=True,
            stderrToServer=True)
except Exception as pydevd_connection_exception:
    LOGGER.exception('Unable to connect to pydevd. Ignoring...', exc_info=pydevd_connection_exception)
