#!/usr/local/bin/perl
#
# change passwords on 3Com switches
#
# $Id: a3compasswd,v 1.3 1999/02/10 15:28:14 trockij Exp $
#
# Copyright (C) 1998 Jim Trocki
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

use A3Com::Password;

sub get_passwd;

$OLDPASS = get_passwd ("Old adm password:");
$NEWPASS = get_passwd ("New adm password:");
$NEWPASS2 = get_passwd ("Confirm new adm password:");

die "new passwords do not match\n" unless ($NEWPASS eq $NEWPASS2);

@success = ();
@failures = ();

$| = 1;

foreach $sw (@ARGV) {

    $begin = time;
    print "$sw...";

    $n = new A3Com::Password;
    $n->switch ($sw);
    $n->login ("adm");
    $n->password ($OLDPASS);
    $n->log (0);

    $result = $n->set_admpassword ($NEWPASS);

    if ($result eq undef) {
	push (@failures, [$sw, $n->error]);
	$s = "fail!";
    } else {
    	push @success, $sw;
	$s = "ok";
    }
    $end = time;

    print "done ($s), ($begin $end) " . $end - $begin . " seconds\n";
}

if (@failures == 0) {
    print "\nAll switches updated successfully\n";
    exit (0);
}

#
# failures!
#
print STDERR "\n#\n# failures occurred:\n#\n";

for (@failures) {
    print STDERR "@{$_}\n";
}

exit (1);


sub get_passwd {
    my $prompt = shift;
    my ($PASS, $oldhandler);

    $prompt = "Password:" if ($prompt eq "");

    $oldhandler = $SIG{"INT"};
    $SIG{"INT"} = \&sigint_handler;
    system "stty -echo";
    print "$prompt ";
    chop ($PASS = <STDIN>);
    print "\n";
    system "stty echo";
    $SIG{"INT"} = $oldhandler;

    $PASS;
}

sub sigint_handler {
    system "stty echo";
    for (@success) { print "$_ changed\n" }
    for (@failures) { print "$_ NOT CHANGED\n" }
    exit;
}
