#!/usr/bin/perl -w
#
# forked off dshbak 1162 2008-04-01 16:11:29Z grondo
# by Alexander Bandura (gmail: xand.bandura) 2010-05-26
# to implement pdsh output split between node-specific
# files in a directory; -f to create outdir first
# 
require 5.003;

use Getopt::Std;
use File::Path;

# deal with arguments
%opt = ();
getopts("fd:",\%opt) or usage();
usage() if not defined $opt{d};

$prefix=$opt{d};
if (defined $opt{f} and ! -d $prefix) {
    mkpath($prefix);
}
-d $prefix or die "$0: output directory does not exist!\n";

#
# Stdin consists of lines of the form "hostname: output...".
# Store these in a hash, keyed by hostname, of lists of lines.
#
while (<>) {
	($tag, $data) = m/^\s*(\S+?)\s*: ?(.*\n)$/;
	push(@{$lines{$tag}}, $data);
}

	foreach $tag (sortn(keys %lines)) {
		open(FD,">$prefix/$tag");
		foreach $data (@{$lines{$tag}}) {	# lines of data
			print FD $data;
		}
	}

sub usage
{
	printf STDERR ("Usage: $0 -d <outdir> [-f]\n");
	exit 1;
}

# 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*)$/]} @_;
}
