#!/usr/bin/ruby -w

require 'fileutils'
require 'tempfile'

if !File.directory?('/etc/etchserver/trunk')
  abort "Please check out an etch config repo in /etc/etchserver/trunk"
end

FileUtils.mkdir_p('/etc/etchserver/orig')
FileUtils.chown('nobody', nil, '/etc/etchserver/orig')
Dir.chdir('/etc/etchserver')
system('svn update --quiet')

# Create hourly tag
FileUtils.mkdir_p('/etc/etchserver/tags')
currenttag = Time.now.strftime('etchautotag-%Y%m%d-%H00')
tagdir = File.join('tags', currenttag)
if !File.directory?(tagdir)
  # Use Tempfile to make a unique filename
  tmpdirfile = Tempfile.new('newtag', 'tags')
  # Turn it into a directory
  File.delete(tmpdirfile.path)
  Dir.mkdir(tmpdirfile.path)
  # Use it to create the new tag atomically
  system("cp -a trunk #{tmpdirfile.path}")
  File.rename(File.join(tmpdirfile.path, 'trunk'), tagdir)
  # Cleanup
  Dir.delete(tmpdirfile.path)
end

def convert_tagtime_to_unixtime(tagdate, tagtime)
  year, month, day = tagdate.unpack('A4A2A2')
  hour, minute = tagtime.unpack('A2A2')
  unixtime = Time.local(year, month, day, hour, minute, 0, 0)
  unixtime
end

# Remove old hourly tags
Dir.chdir('tags')
timelimit = Time.at(Time.now - 60 * 60 * 24 * 3)  # 3 days
Dir.foreach('.') do |entry|
  next unless entry =~ /^etchautotag-(\d{8})-(\d{4})$/
  tagunixtime = convert_tagtime_to_unixtime($1, $2)
  if tagunixtime < timelimit
    FileUtils.rm_rf(entry)
  end
end

