#!/opt/alt/python38/bin/python3
"""
Script runs command and sends message to Sentry if any exceptions occurs.
"""
import logging
import subprocess
import sys

from defence360agent import sentry

logger = logging.getLogger(__name__)


def main(command):
    if not command:
        sys.exit("Expected execution command!")

    sentry.configure_sentry()
    try:
        result = subprocess.run(command,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                check=True)
    except subprocess.CalledProcessError as exc:
        result = exc
        logger.error(
            "Command %r returned non-zero code %s,"
            "\n\t\tStdout: %s,"
            "\n\t\tStderr: %s\n",
            command,
            result.returncode,
            result.stdout.decode("utf-8", "backslashreplace"),
            result.stderr.decode("utf-8", "backslashreplace"),
        )
    sys.stdout.buffer.write(result.stdout)
    sys.stderr.buffer.write(result.stderr)
    sys.exit(result.returncode)


if __name__ == '__main__':
    main(sys.argv[1:])
