#!/bin/bash

# remove-old-backups version 2.2.3

[ -r "/etc/backup.conf" ] && \
  . "/etc/backup.conf"

usage () {
  >&2 echo \
'Usage: remove-old-backups [-n]
Remove backups older than one year, keeping only one backup per month.

Options:
  --help     display this help and exit
  --version  display version and exit
  -n         only print what would be removed'
  [ -n "$1" ] && exit $1
  exit 1
}

no_action=false

if [ $# -eq 1 ]
then
  if [ "x$1" == 'x--help' ]
  then
    usage 0
  elif [ "x$1" == 'x--version' ]
  then
    >&2 echo '2.2.3'
    exit 0
  elif [ "x$1" == 'x-n' ]
  then
    no_action=true
  else
    usage
  fi
elif [ $# -gt 1 ]
then
  usage
fi

removable_backups=$(
  printf '%s\n' "${backups[@]}" | \
    cut -d' ' -f1 | \
    while read -r dir; do \
      ls -1 "$dir" \
      | grep -x '[0-9]\{4\}_[0-9]\{2\}_[0-9]\{2\}' \
      | sort -r \
      | sed '
        1,40d
        s,^,'"${dir}"',
      '
    done
)

if ! ${no_action}; then
  pidFile='/tmp/remove-old-backups.pid'
  [ -s "${pidFile}" ] && [ -d "/proc/$(cat "${pidFile}")" ] && exit 5
  echo $$ > "${pidFile}"
fi

if [ -z "${removable_backups}" ]; then
  exit
fi

printf '%s\n' "${removable_backups}" \
| while read -r dir; do
  echo rm -rf --one-file-system "${dir:?}"
  if ! ${no_action}; then
    rm -rf --one-file-system "${dir:?}"
  fi
done
