#!/bin/bash

## Simple logrotate script
## http://superglue.it | Danja Vasiliev, 2014
##
## Takes filepath or file mask as argument:
##   logrotate /www/access.log [/www/error*.log]
## and gzip compresses them inplace

## default settings
## override in config file mentioned below 

_ROTATE=30  ## backlogs to keep, days
_DATE=$(date +%d.%m.%y-%H:%M:%S)
_LOGS=( $* )

## read config file 
_CONF='/etc/logrotate.conf'
[[ -e $_CONF ]] && . $_CONF

function err {
  local _ERR=$?
  printf %s": "%s"\n" "$(basename $0)" "$1"
  exit $_ERR
}

[[ -n $_LOGS ]] || err 'missing input file'
[[ -e $_LOGS ]] || err 'input file not readable'

for _FILE in ${_LOGS[@]}; do
  ## get number of backlogs and purge unwanted
  _NUM=( $(ls -1 -r $_FILE*.gz &>/dev/null || echo '') ) 
  [[ ${#_NUM[@]} -gt $((_ROTATE-1)) ]] && rm -f ${_NUM[@]:$((_ROTATE-1)) }
  ## compress and move
  gzip -f $_FILE || err 'failed to gzip file'
  mv $_FILE.gz "$_FILE"-"$_DATE".gz || err 'failed to rename archive'
done

exit $?
