#!/usr/bin/perl
#use Fcntl q{:flock};
#use Mooix::Thing; 
run sub {
	my $this=shift;
	%_=@_;
	my $id=$_{hint};

	if (exists $_{mkdir} && ! $this->dir_ok) {
		$this->usage("dir_ok not set; mkdir not allowed");
	}
	
	# Sanitize the id.
	$id =~ s/[^_A-Z0-9a-z]/_/g;
	my $num = 0;
	if (! length $id || $id =~ m/\.\./ || $id =~ m#/#) {
		$id = "item";
		$num = 1; # start with item1
	}
	
	# Guard against races.
	my $lock=$this->getlock(LOCK_EX);
	
	# If the hint already exits, just add numbers to it until something
	# is found that does not.
	if ($this->fieldfile($id) || $num) {
		$num = 2 unless $num; # start at 2, so you get "foo2" if
		                      # there is already a "foo".
		while ($this->fieldfile($id.$num)) {
			$num++;
		}
		$id = $id.$num;
	}
	
	if (exists $_{mkdir}) {
		my $oldmask = umask(0);
		mkdir($id, 0777) or $this->croak("mkdir $id");
		umask($oldmask);
	}
	
	return $this->id."/".$id;
}
