#!/usr/bin/python

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; specifically version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright: RedHat 2013-2014
# Author: Lucas Meneghel Rodrigues <lmr@redhat.com>


import sys
try:
    import os
    import tempfile
    import traceback
except:
    sys.stderr.write("Unable to import basic python libraries, please "
                     "reinstall avocado and dependencies.\n")
    # This exit code is replicated from avocado/core/exit_codes.py and not
    # imported because we are dealing with import failures
    sys.exit(-1)


def handle_exception(*exc_info):
    # Print traceback if AVOCADO_LOG_DEBUG environment variable is set
    msg = "Avocado crashed:\n" + "".join(traceback.format_exception(*exc_info))
    if os.environ.get("AVOCADO_LOG_DEBUG"):
        os.write(2, msg + '\n')
    # Store traceback in data_dir or TMPDIR
    crash_dir = None
    prefix = "avocado-traceback-"
    try:
        import time
        prefix += time.strftime("%F_%T") + "-"
        from avocado.core import data_dir
        _crash_dir = os.path.join(data_dir.get_data_dir(), "crashes")
        os.makedirs(_crash_dir)
        crash_dir = _crash_dir
    except:
        pass
    tmp, name = tempfile.mkstemp(".log", prefix, crash_dir)
    os.write(tmp, msg.encode('utf-8'))
    os.close(tmp)
    # Print friendly message in console-like output
    msg = ("Avocado crashed unexpectedly: %s\nYou can find details in %s"
           % (exc_info[1], name))
    os.write(2, msg + '\n')
    # This exit code is replicated from avocado/core/exit_codes.py and not
    # imported because we are dealing with import failures
    sys.exit(-1)


if __name__ == '__main__':
    sys.excepthook = handle_exception


# simple magic for using scripts within a source tree
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if os.path.isdir(os.path.join(basedir, 'avocado')):
    os.environ['PATH'] += ":" + os.path.join(basedir, 'scripts')
    os.environ['PATH'] += ":" + os.path.join(basedir, 'libexec')
    sys.path.append(basedir)


from avocado.core.app import AvocadoApp


if __name__ == '__main__':
    # Override tmp in case it's not set in env
    for attr in ("TMP", "TEMP", "TMPDIR"):
        if attr in os.environ:
            break
    else:   # TMP not set by user, use /var/tmp if exists
        # TMP not set by user in environment. Try to use /var/tmp to avoid
        # possible problems with "/tmp" being mounted as TMPFS without the
        # support for O_DIRECT
        if os.path.exists("/var/tmp"):
            os.environ["TMP"] = "/var/tmp"
    app = AvocadoApp()
    sys.exit(app.run())
