#!/usr/bin/python3

import os
import sys
import shlex
import subprocess
import re

# read parameters
prefix = os.getenv('PREFIX')

VARSUFFIX = '_RUN'

for k, v in os.environ.items():
    if not k.endswith(VARSUFFIX):
        continue

    name = k[:-len(VARSUFFIX)]
    lineno = int(os.getenv('{}_LINE'.format(name), '0'))
    grep = os.getenv('{}_GREP'.format(name), '')
    case = int(os.getenv('{}_CASE'.format(name), '1'))

    cm = os.getenv(f'{name}_CM', 'string')
    if cm == 'string':
        def_cmargs = 'options=reinit dynamic'
    else:
        def_cmargs = ''

    cmargs = os.getenv(f'{name}_CMARGS',def_cmargs)

    if case == 0:
        grep_opts = re.IGNORECASE
    else:
        grep_opts = 0

    line = ''
    try:
        r = subprocess.run(shlex.split(v), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    except Exception as e:
        line = str(e)
    else:
        lines = r.stdout.decode().strip().split('\n')

        if grep:
            lines = list(filter(lambda s: re.search(grep, s, grep_opts), lines))
        try:
            line = lines[lineno]
        except IndexError:
            line = ''

    print(f'NAME: {prefix}{name}')
    print(f'TAGS: run')
    print(f'DETAILS: {line}')
    print(f'METHOD: {cm}|{cmargs}')
    print(f'STATUS: {line}')
    print()
