#!/usr/bin/env ruby

# Compresses haproxy log for the previous month.
#
#  - m.barnaba@ifad.org  Tue Mar 29 13:50:52 CEST 2016
#
# rm log dir after compression
#
#  - m.barnaba@ifad.org  Fri Apr  8 01:38:29 CEST 2016
#
LOGS = '/var/log/haproxy'

require 'time'

now = Time.now
logdate = (Time.new(now.year, now.month, 1, 0, 0, 0) - 1)

month, year = [ '%02d' % logdate.month, '%d' % logdate.year ]

yeardir  = "#{LOGS}/#{year}"
monthdir = "#{LOGS}/#{year}/#{month}"
archive  = "#{monthdir}.tar.gz"

unless File.exists? monthdir
  abort "ERROR: logs directory #{monthdir} does not exist"
end

if File.exists? archive
  abort "ERROR: #{archive} already exists"
end

_, status = Process.wait2(Process.spawn("tar cfz #{archive} -C #{yeardir} #{month}"))

unless status.success?
  abort "ERROR: archive creation exited with status #{status.exitstatus}"
end

_, status = Process.wait2(Process.spawn("rm -rf #{monthdir}"))

unless status.success?
  abort "ERROR: clean up of monthdir exited with status #{status.exitstatus}"
end

# Now remove archives older than 24 months ago
Dir["#{LOGS}/**/*.tar.gz"].
  select {|f| File.stat(f).ctime.to_date < (Date.today << 24) }.
  each {|f| File.unlink(f) }
