#!/opt/alt/python35/bin/python3.5
"""
This program is free software: you can redistribute it and/or modify it under 
the terms of the GNU General Public License as published by 
the Free Software Foundation, either version 3 of the License, 
or (at your option) any later version.


This program is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
See the GNU General Public License for more details.


You should have received a copy of the GNU General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/>.

Copyright © 2019 Cloud Linux Software Inc.

This software is also available under ImunifyAV commercial license,
see <https://www.imunify360.com/legal/eula>


Script runs command and sends message to Sentry if any exceptions occurs.
"""
import json
import logging
import platform
import os
import subprocess
import sys
from typing import List
from contextlib import suppress

import sentry_sdk

logger = logging.getLogger(__name__)


IMUNIFY360 = "imunify360"
IMUNIFYAV = "imunify-antivirus"
IMUNIFY360_PKG = "imunify360-firewall"
LICENSE = "/var/imunify360/license.json"
LICENSE_FREE = "/var/imunify360/license-free.json"
FREE_ID = "IMUNIFYAV"
UNKNOWN_ID = "UNKNOWN"
SENTRY_DSN = "https://831a73da71fc4a6abe776f7d0adcc48d:3b9c6c32229744388f98e85dc9104da2@sentry.cloudlinux.com/3?timeout=20"  # noqa: E501
ERROR_MSG_TEMPLATE = (
    "Command {cmd!r} returned non-zero code {result.returncode},\n"
    "\t\tStdout: {result.stdout},\n"
    "\t\tStderr: {result.stderr}\n"
)


def get_server_id() -> str:
    with suppress(Exception):
        for filename in [LICENSE, LICENSE_FREE]:
            with suppress(FileNotFoundError), open(filename) as file:
                return json.load(file)['id']
    return UNKNOWN_ID


def collect_output(cmd: List[str]) -> str:
    try:
        cp = subprocess.run(cmd, stdin=subprocess.DEVNULL,
                            stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    except OSError:
        return ''
    if cp.returncode != 0:
        return ''
    return os.fsdecode(cp.stdout)


def get_rpm_version(pkg: str) -> str:
    cmd = ['rpm', '-q', '--queryformat=%{VERSION}-%{RELEASE}', pkg]
    return collect_output(cmd)


def get_dpkg_version(pkg: str) -> str:
    cmd = ['dpkg-query', '--showformat=${Version}', '--show', pkg]
    return collect_output(cmd)


def get_current_os():
    platform_os = platform.linux_distribution()[0]
    return platform_os.lower()


def get_package_name():
    platform_os = get_current_os()
    service_name = IMUNIFY360_PKG
    if platform_os != 'ubuntu' and get_rpm_version(IMUNIFYAV):
        service_name = IMUNIFYAV
    else:
        service_name = IMUNIFY360
    return service_name


def get_service_version(service_name) -> str:
    platform_os = get_current_os()
    if platform_os != 'ubuntu':
        version = get_rpm_version(service_name)
    else:
        version = get_dpkg_version(service_name)
    return version


def configure_sentry():
    # using LoggingIntegration (contained in default Integrations)
    # logging event with *error* level will be reported to Sentry automatically
    sentry_sdk.init(dsn=SENTRY_DSN)
    with sentry_sdk.configure_scope() as scope:
        package = get_package_name()
        scope.user = {'id': get_server_id()}
        scope.set_tag('name', package)
        scope.set_tag('version', get_service_version(package))


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

    configure_sentry()
    try:
        result = subprocess.run(command,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                check=True)
    except subprocess.CalledProcessError as exc:
        result = exc
        logger.error(ERROR_MSG_TEMPLATE.format(cmd=command, result=result))

    sys.stdout.buffer.write(result.stdout)
    sys.stderr.buffer.write(result.stderr)
    sys.exit(result.returncode)


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