#!/usr/bin/perl
#use Mooix::Thing;
use IPC::Open2;
use Mooix::Conf;
run sub {
	my $this=shift;
	%_=@_;
	my $session = $_{session} || $this->croak("bad session");
	
	# Make sure that this command is not spoofed, just in case.
        if ($_{avatar} != $this) {
		fail "No!"; 
	}

	my @users = $this->users;
	if (@users > 1) {
		$session->write("More than one unix user can use your avatar; changing the password of the first.");
	}
	if (@users == 0) {
		fail "Cannot determine unix user for your avatar, so cannot change the password.";
	}
	
	my $user=$users[0];
	if ($user !~ /^\Q$Mooix::Conf::field{moouserprefix}\E/) {
		fail "Unix user $user is not a moo-only user, so not changing the password.";
	}
	
	# So moopasswd can be found.
	$ENV{PATH}=$Mooix::Conf::field{safepath};
	
	# This setuid helper program takes care of prompting and setting
	# the password. It outputs a line, then reads a line, so a
	# bi-directional pipe is needed. After all this work, it will look
	# nearly identical to just running "passwd", but this way the
	# session can be changed..
	my $pid = open2(\*READ, \*WRITE, 'moopasswd', $user);
	while (<READ>) {
		chomp;
		my ($command, $text) = split(/: /, $_, 2);
		my $res;
		if ($command eq 'prompt') {
			$res = $session->prompt(prompt => $text);
		}
		elsif ($command eq 'password') {
			$res = $session->password(prompt => $text);
		}
		elsif ($command eq 'write') {
			$res='';
			$session->write($text);
		}
		print WRITE $res."\n";
	}
	waitpid $pid, 0;
	if ($?) {
		fail "Password change failed.";
	}
	else {
		$session->write("Password changed.");
	}
}
