#!/usr/bin/env python3
import asyncio
import sys
from signal import SIGINT, SIGTERM

from gql.cli import get_parser, main

# Get arguments from command line
parser = get_parser(with_examples=True)
args = parser.parse_args()

try:
    # Create a new asyncio event loop
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    # Create a gql-cli task with the supplied arguments
    main_task = asyncio.ensure_future(main(args), loop=loop)

    # Add signal handlers to close gql-cli cleanly on Control-C
    for signal in [SIGINT, SIGTERM]:
        loop.add_signal_handler(signal, main_task.cancel)

    # Run the asyncio loop to execute the task
    exit_code = 0
    try:
        exit_code = loop.run_until_complete(main_task)
    finally:
        loop.close()

    # Return with the correct exit code
    sys.exit(exit_code)
except KeyboardInterrupt:
    pass
