#!/usr/bin/perl
#use Fcntl q{:flock};
#use Mooix::Thing;
use Mooix::CallStack;
run sub {
	my $this=shift;
	%_=@_;
	my $session = $_{session} or return;
	
	# This method should be run by reap or directly via runmeth.
	# Or, it can be run by a the avatar who the session belongs to.
	my $avatar=$session->avatar;
	my $stack=Mooix::CallStack->get;
	#$stack=$stack->nextsegment;
	my $b=0;
	while ($stack) {
		$b++ if $stack->boundry;
		last if $b >= 2;
		if ($avatar && $stack->index != $avatar->index &&
		    $stack->index != $this->index) {
			die "bad caller ".$stack->index;
		}
		$stack=$stack->next;
	}
	
	# Take an exclusive lock on the session to prevent nastiness if two
	# logouts are racing on the same session. That happens a lot if the
	# moo is shut down with someone logged in.
	my $fh = $session->getlock(LOCK_EX);
	# If we lost a race getting the lock, the session could be gone at
	# this point.
	if (-d $session->id) {
		$session->write("Logging out.") unless $_{quiet};
		$session->avatar->logout(session => $session, quiet => $_{quiet}) if $session->avatar;
		# Record login duration to lastlog.
		if (ref $this->lastlog && ! $_{nolog}) {
			my $lastlogid = $session->lastlogid;
			my %loginfo = $this->lastlog->loginfo(id => $lastlogid);
			my $duration = time - $loginfo{login};
			$this->lastlog->edit(id => $session->lastlogid, duration => $duration);
		}
	}
	$this->sessions->remove(object => $session);
}
