#!/usr/bin/env python
'''
Copyright (C) 2014, Digium, Inc.
Torrey Searle <torrey@voxbone.com>,
Walter Doekes <walter+asterisk@wjd.nu>

This program is free software, distributed under the terms of
the GNU General Public License Version 2.
'''

import sys
import os
import logging

sys.path.append("lib/python")
sys.path.append("utils")

from tempfile import NamedTemporaryFile
from twisted.internet import reactor
from asterisk.sipp import SIPpTest

WORKING_DIR = os.path.abspath(os.path.dirname(__file__))
TEST_DIR = os.path.dirname(os.path.realpath(__file__))

logger = logging.getLogger(__name__)


def main():
    sipplog = NamedTemporaryFile(delete=True)

    SIPP_SCENARIOS = [
        {
            'scenario': 'invite.xml',
            '-i': '127.0.0.1',
            '-p': '5061',
            '-s': '3200000000',
            '-message_file': sipplog.name,
            # Cheat and pass two argumentless options as key and value
            # because the SIPpTest doesn't allow us to pass ordered-args.
            # We use -pause_msg_ign to ignore messages while being paused
            # and then check the log (from -trace_msg) for those messages.
            '-trace_msg': '-pause_msg_ign',
        }
    ]

    test = SIPpTest(WORKING_DIR, TEST_DIR, SIPP_SCENARIOS)
    test.reactor_timeout = 10

    reactor.run()

    # If it failed, bail.
    if not test.passed:
        return 1

    # If it succeeded, check if any 503 errors snuck into the log while
    # we were on pause.
    sipplog.seek(0)
    for line in sipplog:
        if 'SIP/2.0 5' in line:
            # Collect entire message for debugging purposes.
            debug = [line]
            for line in sipplog:
                if not line.strip():
                    break
                debug.append(line)
            logger.warn('Got unexpected SIP message:\n' + ''.join(debug))
            # Bail.
            return 1

    return 0


if __name__ == "__main__":
    sys.exit(main())

# vim:sw=4:ts=4:expandtab:textwidth=79
