#!/usr/bin/perl
# This helper method must be stackless.
#use Mooix::Thing;
use Mooix::CallStack;

run sub {
	my $this=shift;

	# Only the destroy method may call this one. That method uses
	# candestroy to make sure that the callstack can indeed destroy this
	# object.
	if (! Mooix::CallStack::calledby($this, 'destroy')) {
		$this->croak("only the destroy method can call this method");
	}

	# Send a SIGTERM to all running methods of the object (except this
	# one), to let well-behaved methods know it's time to die.
	$ENV{MOOIX_NONSTANDARD}=1;
	kill(15, 0);
	delete $ENV{MOOIX_NONSTANDARD};
	
	# Loop over the fields in the object's directory, only.
	opendir(DIR, ".") or return 1; # failure
	while (my $field = readdir(DIR)) {
		next if $field eq '.' || $field eq '..' || $field eq '.mooix' || $field eq 'parent';
		if (-d $field && ! -l $field) {
			# The ony supported use of subdirectories of objects is
			# objects that contain other objects. Thus, get rid of
			# the subdirectory by asking the encapsulated object
			# to destroy itself.
			if (! ref $this->$field) {
				print STDERR "warning: $this->$field is a directory but not a mooix object\n";
			}
			if ($this->$field->destroy) { # inverted return code
				return 1; # failure
			}
		}
		else {
			unlink($field) or return 1; # failure
		}
	}
	
	# Remove .mooix field. This also (magically) makes the directory
	# itself and any remaining contents (the parent link particularly)
	# be removed, and sends a SIGKILL to any remaining running methods
	# including this one.
	unlink(".mooix") or return 1; # failure

	# This should never be reached.
	return 1; # failure
}
