#!/bin/bash

fail() {
  echo "$1" >&2
  /usr/bin/logger -t logrotate "$1"
  exit 1
}

# Use flock to ensure only one instance at a time can run, by wrapping the
# whole of the rest of the script in a subshell with (otherwise unused) file
# descriptor 123 redirected to the lock file.
(
flock --exclusive --nonblock 123 || \
  exit 0

# First delete as many old compressed logs as necessary.
/opt/xensource/bin/delete_old_logs_by_space

# Then rotate the live logs if needed, i.e. the uncompressed files to which
# processes are logging data.
/opt/xensource/bin/rotate_logs_by_size

) 123>/dev/shm/logrotate_script.lock
# Reasoning for using /dev/shm rather than /var/run:
# Since this script is for freeing disc space, we want it to work even when the
# disc is full. Therefore put the lock-file on /dev/shm which is backed by
# memory not disc.

exit 0
