#!/usr/bin/env python3

from sys import argv
from subprocess import check_output as sh

if len(argv) == 3:
    m = argv[1]
    q = argv[2]
elif len(argv) != 2:
    print('Usage:', argv[0], '<query>')
    exit(1)
else:
    m = 'sk'
    q = argv[1]

dir = '/home/zgrep/offtopiabday/'

lines = []
with open(dir + 'starter') as fh:
    for line in fh:
        if q in line:
            lines.append(line.strip())

if 'k' in m or 'r' in m:
    modlin = [' '.join(x.split()[:3]) for x in lines]

    pids = []
    out = sh(['ps']).decode().split('\n')[1:]
    for line in out:
        if any(l in line for l in modlin):
            print(line)
            pids.append(line.split()[0])

    if pids and 'k' in m:
        print('\nKill the above? (Y/N)')
        if input().strip().lower() != 'y':
            print('Not killing.')
            exit(0)

        for pid in pids:
            print('Killing', pid, end='.\n')
            sh(['kill', pid])
if 's' in m:
    for line in lines:
        print('Starting', line, end='.\n')
        sh(line, shell=True)