#!/usr/bin/perl -w

# Most of this code is cut & pasted from Hostlist.pm in the Genders
# project.  See http://sourceforge.net/projects/genders/

use strict;

# Turn long lists of nodes with numeric suffixes into ranges where possible
# optionally return a Quadrics-style range if $quadrics_ranges is nonzero.
#
#   @nodes (IN)         flat list of nodes
#   RETURN              list of nodes possibly containing ranges
#
sub compress {
    my %rng = comp2(@_);
    my @list = ();

    local $"=",";

    @list = map {  $_ .
		       (@{$rng{$_}}>1 || ${$rng{$_}}[0] =~ /-/ ?
			"[@{$rng{$_}}]" :
			"@{$rng{$_}}"
		       )
    } sort keys %rng;

    return wantarray ? @list : "@list";
}

# comp2():
#
# takes a list of names and returns a hash of arrays, indexed by name prefix,
# each containing a list of numerical ranges describing the initial list.
#
# e.g.: %hash = comp2(lx01,lx02,lx03,lx05,dev0,dev1,dev21)
#       will return:
#       $hash{"lx"}  = ["01-03", "05"]
#       $hash{"dev"} = ["0-1", "21"]
#
sub comp2
{
    my (%i) = ();
    my (%s) = ();

        # turn off warnings here to avoid perl complaints about
        # uninitialized values for members of %i and %s
    local ($^W) = 0;
    push(@{
	$s{$$_[0]}[ (
			$s{ $$_[0] }[ $i{$$_[0]} ]
			[$#{$s{$$_[0]}[$i{$$_[0]}]}] == ($$_[1]-1)
		    ) ? $i{$$_[0]} : ++$i{$$_[0]}
                         ]
	 }, ($$_[1])
        ) for map { [/(.*?)(\d*)$/] } sortn(@_);

    for my $key (keys %s) {
	@{$s{$key}} =
	    map { $#$_>0 ? "$$_[0]-$$_[$#$_]" : @{$_} }  @{$s{$key}};
    }


    return %s;
}

# sortn:
#
# sort a group of alphanumeric strings by the last group of digits on
# those strings, if such exists (good for numerically suffixed host lists)
#
sub sortn
{
    map {$$_[0]} sort {($$a[1]||0)<=>($$b[1]||0)} map {[$_,/(\d*)$/]} @_;
}

if (@ARGV == 0) {
    my $prog = `basename $0`;

    chomp($prog);
    print "Usage: $prog <node1> <node2> <node3> ...\n";
    print "  e.g. $prog node8 node152 node24\n";
    exit 1;
}

my $compressednodes = compress(@ARGV);

print "$compressednodes\n";

exit 0;
