#!/bin/sh

# This script is used to find and remove the oldest logfile on the SD card.
# For determination of the oldest file, the modification date of the files are used. 

# Get the filename of the oldest file
filenames=$(find /opt/card/ -name "*_LAN*.xml" -o -name "*_TP*.xml" -o -name "*_LAN*.trx" -o -name "*_TP*.trx" | sort )

if [ "$filenames" != "" ]; then
  filename=$(echo "$filenames" | xargs ls -tr | head -n1 )

  # Remove the file
  rm -f "$filename"
  # Save exit code of operation for returning. 
  ERR=$?
  # To clean up empty directories get directory path
  filedir=$(dirname "$filename")
  # If the directory is empty, delete it
  if [ "$(ls -A $filedir)" = "" ]; then
    rmdir -p "$filedir"
  fi
fi

exit $ERR

