#!/usr/bin/env python
'''
Copyright (C) 2011, Digium, Inc.
Jonathan Rose <jrose@digium.com>

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

import fileinput
import sys
import os
import time
import logging
import shutil
from twisted.internet import reactor, defer
from starpy import fastagi

sys.path.append("lib/python")
from asterisk.asterisk import Asterisk
from asterisk.version import AsteriskVersion
from asterisk.test_case import TestCase
from asterisk.cdr import AsteriskCSVCDR, AsteriskCSVCDRLine
from starpy import manager

LOGGER = logging.getLogger(__name__)

# Quick little function for doing search and replace in a file used below.
def file_replace_string(file, search, replace):
    for line in fileinput.input(file, inplace=1):
        if search in line:
            line = line.replace(search,replace)
        sys.stdout.write(line)

"""
This test case creates two Asterisk instances with TLS enabled.
ast[0] calls ast[1] using a TLS encrypted SIP peer and ast[1] waits a little while then plays DTMF of '5'
back. If all goes well, this will create a manager event on ast[0] indicating it received a DTMF tone of '5'.
"""
class SIPTLSCallTest(TestCase):

    # Preps test objects and configuration additions as well as copies TLS keys to test folder.
    def __init__(self):
        TestCase.__init__(self)

        # Additional setup for config files and keys
        LOGGER.info("Building test resources ...")
        if os.path.exists('%s/configs/ast1/sip_helper.inc' % self.test_name):
            os.remove('%s/configs/ast1/sip_helper.inc' % self.test_name)
        shutil.copy('%s/configs/helper1' % self.test_name, '%s/configs/ast1/sip_helper.inc' % self.test_name)

        if os.path.exists('%s/configs/ast2/sip_helper.inc' % self.test_name):
            os.remove('%s/configs/ast2/sip_helper.inc' % self.test_name)
        shutil.copy('%s/configs/helper2' % self.test_name, '%s/configs/ast2/sip_helper.inc' % self.test_name)
        file_replace_string('%s/configs/ast1/sip_helper.inc' % self.test_name, '<<path>>', self.test_name)
        file_replace_string('%s/configs/ast2/sip_helper.inc' % self.test_name, '<<path>>', self.test_name)

        self.create_asterisk(2)

        #Now that we've created the Asterisk instances, let's go ahead and remove the sip_helper.inc files
        if os.path.exists('%s/configs/ast1/sip_helper.inc' % self.test_name):
            os.remove('%s/configs/ast1/sip_helper.inc' % self.test_name)

        if os.path.exists('%s/configs/ast2/sip_helper.inc' % self.test_name):
            os.remove('%s/configs/ast2/sip_helper.inc' % self.test_name)

        # initialize test variables
        self.passed = False
        self.tone1 = False
        self.tone2 = False

    def ami_connect(self, ami):
        if (AsteriskVersion() >= AsteriskVersion('12')):
            ami.registerEvent('DTMFEnd', self.ami_test)
        else:
            ami.registerEvent('DTMF', self.ami_test)

        # We only want to originate the call on the ast[0]'s manager.
        if ami.id == 0:
            LOGGER.info("Originating from SIP/testast1/1000 to 1000@default")
            ami.originate(channel="SIP/testast1/1000",
                          context="default",
                          exten="1000",
                          priority="1").addErrback(self.handle_originate_failure)

    def ami_test(self, ami, event):
        LOGGER.debug("Received DTMF event from AMI %d..." % (ami.id + 1))
        LOGGER.debug("Value of DTMF[digit] = %s" % (event['digit']))
        if event['digit'] == "5" and ami.id == 0:
            self.tone1 = True
            LOGGER.debug("It's a match for ast[0] receiving DTMF from ast[1]")
        elif event['digit'] == "6" and ami.id == 1:
            self.tone2 = True
            LOGGER.debug("It's a match for ast[1] receiving DTMF from ast[0]")

        if self.tone1 and self.tone2:
            LOGGER.info("Both tones have matched at least once. Test PASSED.")
            self.passed = True
            self.stop_reactor()

    def run(self):
        TestCase.run(self)
        self.create_ami_factory(count = 2)


def main():
    test = SIPTLSCallTest()
    reactor.run()

    if test.passed:
        return 0
    return 1

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


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