#!/bin/bash

# Print usage if requested.
if [[ $1 == "--help" || $1 == "-h" ]]
then
    echo "Usage: $0 [files limit] $1 [dir] $2 [filename]"
    exit 0
fi

# The script receives the limit as an argument.
limit=$1
dir=$2
filename=$3

number_of_files=$(ls $dir/$filename* | wc -l)

if [ $number_of_files -gt $limit ]
then
    # There are more files than the limit
    # So we need to remove the older ones.
    cd $dir
    ls -t | tail --lines=+$(expr $limit + 1) | xargs -d '\n' rm
fi
