#!/bin/sh
#
# Script to seek and destroy orphan CLI temp files.
#
# While leos is running, look for CLI temp files in /tmp that do not
# have a corresponding process and remove them.  This helps prevent
# a full ramdisk.  The check is run every 60 seconds.

source /etc/profile

this_script="$(basename $0)"

echo $$ > /var/run/$this_script.pid

while :; do
    sleep 60

    for f in                               \
        /tmp/[0-9].out                     \
        /tmp/[0-9][0-9].out                \
        /tmp/[0-9][0-9][0-9].out           \
        /tmp/[0-9][0-9][0-9][0-9].out      \
        /tmp/[0-9][0-9][0-9][0-9][0-9].out ; do
        if [ -f "$f" ] ; then              # avoid the no match case
            PID=$(basename $f .out)
            if [ ! -d "/proc/$PID" ] ; then
                rm -f $f
            fi
        fi
    done

    for f in                                 \
        /tmp/temp[0-9].*                     \
        /tmp/temp[0-9][0-9].*                \
        /tmp/temp[0-9][0-9][0-9].*           \
        /tmp/temp[0-9][0-9][0-9][0-9].*      \
        /tmp/temp[0-9][0-9][0-9][0-9][0-9].* ; do
        if [ -f "$f" ] ; then              # avoid the no match case
            PID=$(basename $f | sed s/temp// | cut -d. -f1)
            if [ ! -d "/proc/$PID" ] ; then
                rm -f $f
            fi
        fi
    done

done