#!/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 Shell process and remove them.  This helps prevent
# a full ramdisk.  The check is run every 60 seconds.
#
# This procedure is itself inherently weak, because if anybody other
# than a CLI session uses a name that matches these patterns we will
# blindly delete it.
#
# A better approach would be to put the cleanup in the shellMgr
# (session manager) so that when a session goes away we would do the
# tidying up for it.

source /etc/profile

this_script="$(basename $0)"

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

cd /tmp || sh -c 'sleep 60 && exit 1'       ## Shop locally!

# We are _so_ not important, make sure we don't steal CPU from _anybody_.
chrt -pi 0 $$ >/dev/null
renice -n 20 -p $$

# By using find, we will NEVER choke on a too-big /tmp directory.
while :; do     ## Forever, but
    sleep 60    ## not too often...

    # Look for stale state-dump subdirectories.  They're pretty big.
    # (These are the tempPID.NN.d/ directories.)
    find . -maxdepth 1 -regex '\./temp[0-9][0-9]*\.[0-9][0-9]*\.d' -type d |
        while read d; do
            IFS=p. ## Isolate pid and fileId as $3 and $4
            set $d
            unset IFS
            [[ "$#" -eq 5 ]] || continue
            kill -0 $3 2>/dev/null && continue  ## Shell still there?  Skip.
            rm -rf $d   ## Stale state-dump directory, kill it.
        done

    # Look for stale scratch files, FIFO's.  (tempFileNameGet() function.)
    # (These are the tempTID.NN files.)
    find . -maxdepth 1 -regex '\./temp[0-9][0-9]*\.[0-9][0-9]*' \
      \( -type f -o -type p \) |
        while read f; do
            IFS=p. ## Isolate tid and fileId as $3 and $4
            set $f
            unset IFS
            [[ "$#" -eq 4 ]] || continue
            kill -0 $3 2>/dev/null && continue  ## Owner still there?  Skip.
            rm -f $f    ## Stale scratch file or FIFO, kill it.
        done

    # Look for stale Shell/Config/DHCP scratch files, FIFO's.
    # (These are the PID.NN and PID.out files.)
    find . -maxdepth 1 \( -regex '\./[0-9][0-9]*\.[0-9][0-9]*' -o \
                          -regex '\./[0-9][0-9]*\.cookie_out' -o \
                          -regex '\./[0-9][0-9]*\.out' \) \
      \( -type f -o -type p \) |
        while read f; do
            IFS=/. ## Isolate pid and fileId as $3 and $4
            set $f
            unset IFS
            [[ "$#" -eq 4 ]] || continue
            kill -0 $3 2>/dev/null && continue  ## Shell still there?  Skip.
            rm -f $f    ## Stale Shell scratch file or FIFO, kill it.
        done
done
