#!/usr/bin/perl
#
# passwd wrapper for AFS, NIS and Unix passwd
#
# J. Kadlecsik with bug fixes from Lionel Cons
# Fixed for RH 7.2 - prefer kapasswd if available
# J.Polok

# First let's try to find the executables

@Path = ('/bin','/usr/bin','/usr/local/bin','/usr/sue/bin');

foreach $dir (reverse(@Path)) {

	$passwd{'ka'} = "$dir/kapasswd"
                if -x "$dir/kapasswd" || -l "$dir/kapasswd";
	$passwd{'c'} = "$dir/kpasswd"
		if -x "$dir/kpasswd" || -l "$dir/kpasswd";
	$passwd{'n'} = "$dir/yppasswd"
		if -x "$dir/yppasswd" || -l "$dir/yppasswd";
	$passwd{'u'} = "$dir/passwd"
		if -x "$dir/passwd" || -l "$dir/passwd";
}

# AFS should be here, but to be sure we check it

# Prefer kapasswd over kpasswd if available

#if ($passwd{'ka'}) {
#	$passwd{'a'}=$passwd{'ka'};
#	}

if ($passwd{'c'}) {
	$found++;
	$default = "CERN";
	$text = "\tc - CERN account\n";
}

# Even if there is yppasswd, NIS is probably not installed

if ($passwd{'n'}) {

	chop($domain = `domainname`);

	if ($domain =~ /^\S+$/ && $domain ne "(none)") {
		$found++;
		$default = "NIS" unless $default;
		$text .= "\tn - NIS account\n";
	} else {
		delete($passwd{'n'});
		undef $domain;
	}
}

# Most of the users (?) have only AFS passwd

if ($passwd{'u'}) {

	$me = (getpwuid($<))[0];
	open(PW, '/etc/passwd');
	while (<PW>) {
		($name, $pw) = split(':');
		$rootpw = $pw if $name eq 'root';
		$mypw = $pw if $name eq $me;
		last if $name eq $me;
	}
	close(PW);

	if ($mypw &&
	    length($mypw) == length($rootpw) &&
	    (length($mypw) != 1 || $mypw eq $rootpw)) {
		$found++;
		$default = "UNIX" unless $default;
		$text .= "\tu - local account\n";
	} else {
		delete($passwd{'u'});
		undef $rootpw;
		undef $mypw;
	}
}

$pw = $default eq "CERN" ? 'c' :
      $default eq "NIS" ? 'n' :
      'u';

exec($passwd{$pw}, @ARGV) if $found == 1;

$text =~ s/($default[^\n]*)/$1 \[default\]/;

print "Which password do you want to change?\n\n";
print "$text\n";
print "Enter the appropriate letter or hit Return for the default: ";

chop($answer = <STDIN>);
$answer = $pw unless $answer;

$answer =~ tr/A-Z/a-z/;

if ($answer =~ /^(c|n|u)$/ && $passwd{$answer}) {
	exec($passwd{$answer}, @ARGV);
} else {
	print "Sorry, try again.\n";
}
