#! /bin/bash
#Copyright 1998-2022 Stonie R. Cooper, Licensed under the auspices of GPLv3,
# See top-level copyright disclaimer (COPYRIGHT) and license (LICENSE)
# cleanup script for pdinrs and metbox
if [ -f /etc/.metbox ]
then
  METBOX=1
else
  METBOX=0
fi
if [ -f /tmp/cleanup ]
then
  boolean=`ps -elf | grep cleanup | grep -v grep | wc -l | awk -F" " '{print $1}'`
  if [ ${boolean} -gt 2 ]
  then
    exit
  fi
fi

touch /tmp/cleanup

for eachPossibility in `echo /etc/pdinrs/cleanup.config /usr/local/ldm/config/cleanup.config`
do
  if [ -r ${eachPossibility} ]
  then
    for EACHCLEANUP in `cat ${eachPossibility} | grep -v ^# | grep -v grep`
    do
      MOUNT=`echo ${EACHCLEANUP} | awk -F: '{print $1}'`
      DIRCY=`echo ${EACHCLEANUP} | awk -F: '{print $2}'`
      PERCT=`echo ${EACHCLEANUP} | awk -F: '{print $3}'`
      START=`echo ${EACHCLEANUP} | awk -F: '{print $4}'`
      NSTEP=`echo ${EACHCLEANUP} | awk -F: '{print $5}'`
      if [ ${PERCT} -ne 0 ]
      then
        CNT_PERCT=`df -k | grep "${MOUNT}$" | awk -F" " '{print $5}' | awk -F% '{print $1}'`
        while [ ${CNT_PERCT} -ge ${PERCT} ]
        do
          for each_dir in `nice find ${MOUNT}/${DIRCY} -mount -depth -type d`
          do
            nice find ${each_dir} -mount -type f -mmin +${START} -exec rm -f {} \; \
              > /dev/null 2>&1
          done
          CNT_PERCT=`df -k | grep "${MOUNT}$" | awk -F" " '{print $5}' | awk -F% '{print $1}'`
          START=`expr ${START} - ${NSTEP}`
          if [ ${START} -le 0 ]
          then
            break
          fi
        done
        if [ ${METBOX} -eq 0 ]
        then
          nice find ${MOUNT}/${DIRCY}/* -mount -depth -empty -mmin +432000 -exec rmdir {} \; 2> /dev/null
        fi
      else
        for each_dir in `nice find ${MOUNT}/${DIRCY} -mount -depth -type d`
        do
          nice find ${each_dir} -mount -type f -mmin +${START} -exec rm -f {} \; \
            > /dev/null 2>&1
        done
        if [ ${METBOX} -eq 0 ]
        then
          nice find ${MOUNT}/${DIRCY}/* -mount -depth -empty -mmin +432000 -exec rmdir {} \; 2> /dev/null
        fi
      fi
    done
  fi
done
rm -f /tmp/cleanup

LOG_CONFIG=/etc/pdinrs/logrotate.config

if [ -r "${LOG_CONFIG}" ]
then
  for each_logfile in `cat ${LOG_CONFIG}`
  do
    LOGPATH_RM=`echo ${each_logfile} | awk -F: '{print $1}'`
    LOGPATH_NM=`echo ${each_logfile} | awk -F: '{print $2}'`
    boolean=`ls ${LOGPATH_RM} 2> /dev/null | wc -l`
    LOGPATH_NM=`expr ${LOGPATH_NM} - ${boolean}`
    if [ ${LOGPATH_NM} -lt 0 ]
    then
      for each_removed in `ls -t1 ${LOGPATH_RM} 2> /dev/null | \
        tail ${LOGPATH_NM}`
      do
        rm -f ${each_removed}
      done
    fi
  done
fi
