#!/usr/local/bin/perl
#
# Change console passwords on a 3Com switch
#
# Jim Trocki
#
# $Id: 3cpasswd,v 1.2 1999/05/15 19:20:16 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::Sys;
use Getopt::Std;
use Data::Dumper;

sub help;
sub get_pw;

getopts ("h", \%opt);

help() if ($opt{"h"} || @ARGV == 0);

$COMM = A3Com::Sys::get_password ("Write community: ");

die "no community specified\n" if ($COMM =~ /^\s*$/);

my %v = ();

print "Type 'none' for no password, <CR> to not change\n";

$READ  = get_pw ("Read login");
die "passwords differ\n" if (!defined $READ);
if ($READ ne "") {
    $v{"read"} = $READ eq "none" ? "" : $READ;
}

$WRITE = get_pw ("Write login");
die "passwords differ\n" if (!defined $WRITE);
if ($WRITE ne "") {
    $v{"write"} = $WRITE eq "none" ? "" : $WRITE;
}

$ADMIN = get_pw ("Admin login");
die "passwords differ\n" if (!defined $ADMIN);
if ($ADMIN ne "") {
    $v{"adm"} = $ADMIN eq "none" ? "" : $ADMIN;
}

foreach $HOST (@ARGV) {
    my ($r, $v) = A3Com::Sys::console_password (
	host => $HOST,
	community => $COMM,
	%v,
    );

    if (!defined $r) {
	print "$HOST not changed: $v\n";
	next;
    }

    print "$HOST passwords changed\n";
}


sub help {
    print <<EOF;
usage: 3cpasswd host [host...]

    Changes read/write/admin console password on a 3Com switching
    device.

    SNMP write community is accepted from an interactive prompt if stdin
    is a tty, otherwise from stdin.

EOF
    exit;
}


sub get_pw {
    my $p = shift;

    my $f = A3Com::Sys::get_password ("$p: ");
    return $f if ($f eq "" or $f eq "none");

    my $s = A3Com::Sys::get_password ("$p (again): ");
    return undef if ($f ne $s);

    return $f;
}

