#! /usr/bin/ruby

# Given a directory, print the filenames of all but the last (alphabetically) n files
# printed filenames are separated by a \0 character, suitable for use with xargs -0
#
# Copyright (c) 2005 Florian Reitmeir
#
# MIT license
#

require 'optparse'

$NULL = nil
$dir = nil
$num_to_keep = 0
$prefix = nil

def show_help(parser, code=0, io=STDOUT)
  io.puts parser
  exit(code)
end
ARGV.options do |opts|
	opts.on_tail("-h", "--help", "Display this help screen") { show_help(opts) }
	opts.on("-p", "--path=PATH", String, "path to cleanup") { |$dir| }
	opts.on("-n", "--number=NUMBER", Integer, "number of entries to keep") { |$num_to_keep| }
	opts.on("-x", "--prefix=PREFIX", String, "prefix of files") { |$prefix| }
	opts.on("-0", "--null", String, "terminate strings with zero") { $NULL = 1 }
	opts.parse!
end

show_help(ARGV.options,1,STDERR) unless $num_to_keep
show_help(ARGV.options,1,STDERR) if $num_to_keep < 1
show_help(ARGV.options,1,STDERR) unless $dir
show_help(ARGV.options,1,STDERR) unless $prefix

entries = Dir.glob($dir + '/' + $prefix+"*").sort.reverse

if entries.length < $num_to_keep
	exit
end

while entries.length > $num_to_keep
	unless $NULL then
		puts entries.pop
	else
		$> << entries.pop << "\0"
	end
end