#!/usr/bin/python3
""" amdgpu-ls  -  Displays details about installed AMD GPUs

    This utility displays most relevant parameters for installed and compatible AMD GPUs. The default
    behavior is to list relevant parameters by GPU.  OpenCL platform information is added when the
    *--clinfo* option is used.  A simplified table of current GPU state is displayed with the *--table*
    option. The *--no_fan* can be used to ignore fan settings.  The *--pstate* option can be used to
    output the p-state table for each GPU instead of the list of basic parameters.  The *--ppm* option
    is used to output the table of available power/performance modes instead of basic parameters.

    Copyright (C) 2019  RueiKe

    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/>.
"""
__author__ = 'RueiKe'
__copyright__ = 'Copyright (C) 2019 RueiKe'
__credits__ = ['Craig Echt - Testing, Debug, Verification, and Documentation']
__license__ = 'GNU General Public License'
__program_name__ = 'amdgpu-ls'
__version__ = 'v3.0.0'
__maintainer__ = 'RueiKe'
__status__ = 'Stable Release'
__docformat__ = 'reStructuredText'
# pylint: disable=multiple-statements
# pylint: disable=line-too-long

import argparse
import sys
from GPUmodules import GPUmodule as gpu
from GPUmodules import env


def main():
    """
    Main flow for amdgpu-ls.
    :return:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--about', help='README',
                        action='store_true', default=False)
    parser.add_argument('--table', help='Output table of basic GPU details',
                        action='store_true', default=False)
    parser.add_argument('--pstates', help='Output pstate tables instead of GPU details',
                        action='store_true', default=False)
    parser.add_argument('--ppm', help='Output power/performance mode tables instead of GPU details',
                        action='store_true', default=False)
    parser.add_argument('--clinfo', help='Include openCL with card details',
                        action='store_true', default=False)
    parser.add_argument('--no_fan', help='do not include fan setting options',
                        action='store_true', default=False)
    parser.add_argument('-d', '--debug', help='Debug output',
                        action='store_true', default=False)
    args = parser.parse_args()

    # About me
    if args.about:
        print(__doc__)
        print('Author: ', __author__)
        print('Copyright: ', __copyright__)
        print('Credits: ', __credits__)
        print('License: ', __license__)
        print('Version: ', __version__)
        print('Maintainer: ', __maintainer__)
        print('Status: ', __status__)
        sys.exit(0)

    env.GUT_CONST.DEBUG = args.debug
    if args.no_fan:
        env.GUT_CONST.show_fans = False

    if env.GUT_CONST.check_env() < 0:
        print('Error in environment. Exiting...')
        sys.exit(-1)

    # Get list of GPUs and get basic non-driver details
    gpu_list = gpu.GpuList()
    gpu_list.set_gpu_list(clinfo_flag=True)

    # Check list of GPUs
    num_gpus = gpu_list.num_vendor_gpus()
    print('Detected GPUs: ', end='')
    for i, (k, v) in enumerate(num_gpus.items()):
        if i:
            print(', {}: {}'.format(k, v), end='')
        else:
            print('{}: {}'.format(k, v), end='')
    print('')
    if 'AMD' in num_gpus.keys():
        env.GUT_CONST.read_amd_driver_version()
        print('AMD: {}'.format(gpu_list.wattman_status()))
    if 'NV' in num_gpus.keys():
        print('nvidia smi: [{}]'.format(env.GUT_CONST.cmd_nvidia_smi))

    num_gpus = gpu_list.num_gpus()
    if num_gpus['total'] == 0:
        print('No GPUs detected, exiting...')
        sys.exit(-1)

    # Read data static/dynamic/info/state driver information for GPUs
    gpu_list.read_gpu_sensor_data(data_type='All')

    # Check number of readable/writable GPUs again
    num_gpus = gpu_list.num_gpus()
    print('{} total GPUs, {} rw, {} r-only, {} w-only\n'.format(num_gpus['total'], num_gpus['rw'],
                                                                num_gpus['r-only'], num_gpus['w-only']))

    # Read report specific details
    if args.clinfo:
        if not gpu_list.read_gpu_opencl_data():
            args.clinfo = False

    # Print out user requested details
    if args.pstates:
        gpu_list.read_gpu_pstates()
        gpu_list.print_pstates()
    if args.ppm:
        gpu_list.read_gpu_ppm_table()
        gpu_list.print_ppm_table()
    if not args.pstates and not args.ppm:
        gpu_list.read_gpu_pstates()
        if args.table:
            com_gpu_list = gpu_list.list_gpus(compatibility='readable')
            com_gpu_list.print_table(title='Status of Readable GPUs:')
        else:
            gpu_list.print(args.clinfo)
    sys.exit(0)


if __name__ == '__main__':
    main()
