#!/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'))

    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("NAME: {}{}".format(prefix, name))
    print("TAGS: run")
    print("DETAILS: {}".format(line))
    print("METHOD: string|options=reinit dynamic")
    print("STATUS: {}".format(line))
    print()
