
#!/bin/sh
# File	: purge_dir.sh
# By	: MaartenDeBoer.nl, 210826
# Subject	: Script to pruge files in a dir
PGM=`basename $0|cut -d\. -f1`
VER="0.1"
LOG="${HOME}/log/${PGM}.log"
DCHR="."
LIST=""
PURGEDIR="."
PURGE=""
PURGECNT=10

USAGE()
{
  echo "Usage: ${PGM} [<options>]"
  echo "  Version: ${VERSION}"
  echo "  options                    :"
  echo "    -c <delimiter character> : define delimiter Character (${DCHR})"
  echo "    -d <directory>           : Directory which need to purged (${PURGEDIR})"
  echo "    -l                       : List the files to be purged"
  echo "    -n <nr>                  : Number of files to keep"
  echo "    -p                       : do Purge"
  echo "    -h | --help              : this help"
  echo "    -V                       : Version"
  echo "    -x                       : set -x"
}
# Check options
while [ ${#} -ge 1 ]
  do
  case ${1} in
    -c) DCHR="${2}"; shift ;;
    -d) PURGEDIR="${2}"; shift ;;
    -n) PURGENR="${2}"; shift ;;
    -l) LIST=1 ;;
    -p) PURGE=1 ;;
    -h | --help) USAGE; exit 1 ;;
    -V) echo "${PGM}: v${VERSION}"; exit 3 ;;
    -x)  set -x ;;
    *)  echo "Option ${1} not known."; USAGE; exit 1 ;;
  esac
    shift
done

echo "`date` ${PGM} v${VER} started."|tee -a ${LOG}
echo "DCHR=${DCHR}"
echo "LIST=${LIST}"
echo "PURGE=${PURGE}"
echo "PURGENR=${PURGENR}"
echo "PURGEDIR=${PURGEDIR}"
sleep 1

ls -1 ${PURGEDIR}|cut -d${DCHR} -f1|sort -u|while read FNAME
do
  echo ${FNAME}
  if [ ${LIST} ]; then
    ls -1 ${PURGEDIR}/${FNAME}${DCHR}*
  fi  # LIST

# Purge
  if [ ${PURGE} ]; then
    FILECNT=`ls -1r ${PURGEDIR}/${FNAME}${DCHR}*|wc -l`
    REMOVECNT=`expr ${FILECNT} - ${PURGENR}`
    echo "  FILECNT=${FILECNT} REMOVECNT=${REMOVECNT}"
    if [ ${REMOVECNT} -gt 0 ]; then
      ls -1r ${PURGEDIR}/${FNAME}${DCHR}*|tail -${REMOVECNT}| while read RMNAME REST
      do
        echo "  Removing ${RMNAME} ..."|tee -a ${LOG}
        rm -f ${RMNAME}
      done  # RMNAME
    fi  # -gt 0
  fi  # PURGE

done  # ls -1


echo "`date` ${PGM} v${VER} finished."|tee -a ${LOG}

