#!/usr/bin/perl
# select_node v1.0  (c) 31.1.2014 by Andreas Ley  (u) 4.4.2024
# From an identifying string (e.g. VHost name) and a list of cluster nodes
# select an evenly distributed but deterministic node to run on

use locale;
use Getopt::Std;
use Digest::MD5 'md5';

sub usage
{
	my $image = $0;
	$image =~ s!.*/!!;
	print STDERR "Usage: $image [-v] string [node [...]]\n";
	exit(1);
}

getopts('DL:hxv') or &usage;

&usage if (defined($opt_h) || !scalar(@ARGV));

$opt_D = $opt_L if (defined($opt_L));
if (defined($opt_v) || defined($opt_D)) {
	$|=1;
	select((select(STDERR),$|=1)[0]);
}

$string = shift;

if (@ARGV) {
	@nodes = @ARGV;
}
else {
	while (<>) {
		chomp;
		print STDERR "\"$_\"\n" if ($opt_D>1);
		push(@nodes,$_);
	}
}

@list = sort @nodes;
if ($opt_D>0) {
	use Digest::MD5 'md5_hex';
	print STDERR md5_hex($string)," % ",scalar(@list)," = ",unpack('N',md5($string)) % scalar(@list),"\n";
}
print $list[ unpack('N',md5($string)) % @list ],"\n";
