#!/usr/bin/python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.
#

from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import with_statement

import argparse
import os
import shlex
import sys
import traceback

home = os.path.normpath("@quiver_home@")
sys.path.insert(0, os.path.join(home, "python"))

from plano import *

def main():
    set_message_output(sys.stdout)

    parser = argparse.ArgumentParser()

    parser.add_argument("--sender-impl", metavar="IMPL", default="qpid-proton-python")
    parser.add_argument("--sender-options", metavar="OPTIONS", default="")
    parser.add_argument("--receiver-impl", metavar="IMPL", default="qpid-proton-python")
    parser.add_argument("--receiver-options", metavar="OPTIONS", default="")
    parser.add_argument("--peer-to-peer", action="store_true",
                        help="Put the receiver in server mode")
    parser.add_argument("--init-only", action="store_true",
                        help="Initialize and immediately exit")

    args, extra_args = parser.parse_known_args()

    domain = "127.0.0.1:{}".format(random_port())
    address = "//{}/q0".format(domain)

    if args.peer_to_peer:
        args.receiver_options += " --server --passive"

    server_command = ["{}/exec/amqp-test-broker".format(home), domain]

    pair_command = [
        "quiver-pair", address,
        "--sender-impl", args.sender_impl,
        "--sender-options", args.sender_options,
        "--receiver-impl", args.receiver_impl,
        "--receiver-options", args.receiver_options,
    ] + extra_args

    exit_code = 0
    server = None

    if args.init_only:
        return

    try:
        if not args.peer_to_peer:
            server = start_process(server_command)

        call(pair_command)
    except KeyboardInterrupt:
        pass
    except:
        traceback.print_exc()
        exit_code = 1
    finally:
        if server is not None:
            stop_process(server)

        exit(exit_code)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass
