#!/bin/env bash

DIR="/tmp"
# Note: patterns are using BREs.
FILE_PATTERN="maxwell.*events"
PATH_PATTERN=".*/${FILE_PATTERN}"
PROCESS_NAME="java"

# If there are multiple processes with the same name, we'll have to deal with
# a few PIDs. The last PID can be followed by a space, so we strip it before
# converting to comma-separated string that 'lsof' works with.
PIDS=$(pidof ${PROCESS_NAME} | sed 's/[[:blank:]]*$//' | tr ' ' ',')

# Find all events files on filesystem and all open events files.
# Files that are present more then once are likely 'open'. So, we remove
# only unique files from the combined list (assuming each list had no
# duplicates).
{ lsof -p "${PIDS}" | tail -n +2 | awk '{print $NF}' | grep ${FILE_PATTERN};\
find "${DIR}" -maxdepth 1 -type f -regex ${PATH_PATTERN}; }\
| sort | uniq -u | xargs rm
