#!/usr/bin/python
# Copyright 2016, 2017, 2018, 2019 Cumulus Networks, Inc.  All Rights reserved.
#
# This software is subject to the Cumulus Networks End User License Agreement
# available at the following locations:
#
# Internet: https://cumulusnetworks.com/downloads/eula/latest/view/
# Cumulus Linux systems: /usr/share/cumulus/EULA.txt

import subprocess
import os
import sys
import socket
from time import localtime

DATE = '%d%d%d' % (localtime().tm_year, localtime().tm_mon, localtime().tm_mday)
TIME = '%d%d%d' % (localtime().tm_hour, localtime().tm_min, localtime().tm_sec)

SUPPORT_PATH = '/var/support/'
EXTENSION = '.txz'
BASENAME = 'netq_support_%s_%s_%s' % (socket.gethostname(), DATE, TIME)
OUTFILE = '%s%s' % (BASENAME, EXTENSION)

RC_SUCCESS = 0
RC_FAIL = 1

LINUX_CMDS = {
    'ps-aux.txt': ['ps', 'aux'],
    'systemctl.txt': ['systemctl', '-l', '--type', 'service', '--all'],
    'ip-link-show.txt': ['ip', '-d', 'link', 'show'],
    'ip-addr-show.txt': ['ip', 'addr', 'show'],
    'ip-route-show-table-all.txt': ['ip', 'route', 'show', 'table', 'all'],
    'ip-neighbor-show.txt': ['ip', 'neighbor', 'show'],
    'brctl-show.txt': ['brctl', 'show'],
    'bridge-fdb-show.txt': ['bridge', 'fdb', 'show'],
    'bridge-vlan-show.txt': ['bridge', 'vlan', 'show'],
    'ntpq.txt': ['ntpq', '-pn'],
    'timedatectl.txt': ['timedatectl']
}
DEBIAN_UBUNTU_FILES = {
    '/var/log/': ['syslog', 'netq-agent.log', 'netqd.log'],
    '/etc/': ['os-release']
}
DEBIAN_UBUNTU_CMDS = {
    'dpkg.txt': ['dpkg', '-l']
}
CENTOS_RHEL_FILES = {
    '/var/log/': ['messages', 'netq-agent.log', 'netqd.log'],
    '/etc/': ['os-release']
}
CENTOS_RHEL_CMDS = {
    'rpm-qa.txt': ['rpm', '-qa']
}


def support_msg():
    return 'Please send %s%s to Cumulus support.' % (SUPPORT_PATH, BASENAME)


def platform():
    sysname, nodename, release, version, machine = os.uname()

    if 'Ubuntu' in version or 'Cumulus' in version or 'Debian' in version:
        DEBIAN_UBUNTU_CMDS.update(LINUX_CMDS)
        return DEBIAN_UBUNTU_FILES, DEBIAN_UBUNTU_CMDS
    elif 'el7' in release:
        try:
            # brctl is not installed by default
            subprocess.check_output(['yum', 'install', 'bridge-utils.x86_64', '-y'])
        except subprocess.CalledProcessError as ex:
            print('ERROR: %s' % ex.cmd)
        CENTOS_RHEL_CMDS.update(LINUX_CMDS)
        return CENTOS_RHEL_FILES, CENTOS_RHEL_CMDS

    else: # rhel
        try:
            # brctl is not installed by default
            subprocess.check_output(['yum', 'install', 'bridge-utils.x86_64', '-y'])
        except subprocess.CalledProcessError as ex:
            print('ERROR: %s' % ex.cmd)
        CENTOS_RHEL_CMDS.update(LINUX_CMDS)
        return CENTOS_RHEL_FILES, CENTOS_RHEL_CMDS


def copy_files(file_dict):
    files = []
    for path in file_dict:
        for file in file_dict[path]:
            files.append('%s%s' % (path, file))

    try:
        if not os.path.isdir(BASENAME):
            subprocess.check_output(['mkdir', BASENAME])

        for file in files:
            subprocess.check_output(['cp', file, BASENAME])
    except subprocess.CalledProcessError as ex:
        print('ERROR: failed to %s' % ex.cmd)
        return RC_FAIL
    else:
        return RC_SUCCESS


def touch_files(cmd_dict):
    try:
        for file in cmd_dict:
            if file == 'systemctl.txt':
                output = subprocess.check_output(cmd_dict[file]).split()
                services = set()
                for word in output:
                    if 'service' in word:
                        services.add(word)

                properties = 'Names,ActiveState,UnitFilePreset,MainPID,ActiveEnterTimestamp'
                cmd_dict[file] = ['systemctl', 'show', '-p', properties] + list(services)

            with open(file, 'w') as fp:
                subprocess.check_call(cmd_dict[file], stdout=fp)
                subprocess.check_output(['mv', file, BASENAME])

        if not os.path.isdir(SUPPORT_PATH):
            subprocess.check_output(['mkdir', SUPPORT_PATH])

        subprocess.check_output(['tar', '-czvf', '%s%s' % (SUPPORT_PATH, OUTFILE), BASENAME])
        subprocess.check_output(['rm', '-rf', BASENAME])
    except subprocess.CalledProcessError as ex:
        print('ERROR: failed to %s' % ex.cmd)
        return RC_FAIL
    else:
        return RC_SUCCESS


def is_host_server():
    os_info = dict()
    file_path = '/etc/os-release'
    if os.path.isfile(file_path):
        with open(file_path, 'r') as fp:
            for line in fp.readlines():
                pair = line.split('=')
                if len(pair) >= 2:
                    os_info[pair[0]] = pair[1].strip('\"\n')
        return 'NAME' in os_info.keys() and 'cumulus' not in os_info['NAME'].lower()
    else:
        print('ERROR: file {} not found'.format(file_path))
        return False


if __name__ == '__main__':
    if os.getuid():
        print('Must run command as root')
        sys.exit(1)

    if not is_host_server():
        sys.exit(0)  # silently pass for automation tests

    file_dict, cmd_dict = platform()
    if copy_files(file_dict) or touch_files(cmd_dict):
        pass
    else:
        print(support_msg())
