#!/usr/bin/perl
# $Id: bmcinit,v 1.1 2002/09/05 18:23:00 jeffb Exp $
# Cobalt Networks, Inc http://www.cobalt.com
# Copyright 2002 Sun Microsystems, Inc.  All rights reserved.


if($< != 0) { die "You must run this program as root\n" }

#use strict;

use Getopt::Std;
use Data::Dumper;

use vars qw($init $bmc_bin);
my $init_dir = '/etc/rc.d/init.d';
my $init = $init_dir.'/bmcscript';
my $chkconfig = '/sbin/chkconfig';
my $bmc_bin = '/usr/local/cli/server/bmcconfig';

use vars qw($opt_h $opt_P);
#my ($opt_h, $opt_P);
getopts('hP:');

if($opt_h) { usage(); }

my $action;
if(@ARGV) {
	$action = $ARGV[0];	
} else {
	print "You must provide a start or stop argument\n";
	usage();
}


my $word;
if($opt_P) { $word = $opt_P; } 
elsif(check_password()) { $word = check_password(); }
else { $word = get_password(); }
set_password($word);

my $ret;
if($action eq 'start') {
	$ret = enable_startup($word);
} elsif($action eq 'stop') {
	$ret = disable_startup();
}
	
sub get_password
{
	my ($pass, $pass2);
	my $retry = 3;
	for(my $i = 0; $i < $retry; $i++) {
		print "Enter password for BMC: ";		
		system("stty -echo");
		chop($pass = <STDIN>);
		print "\nEnter pasword again: ";
		chop($pass2 = <STDIN>);
		system("stty echo");
		if($pass ne $pass2) {
			print "\nPasswords do not match!\n";
			$pass = 0;
		} else { last; }
	}

	if(!$pass) {
		die "Could not get password, exiting...\n";
	} else { print "\nPassword accepted\n" }
	return $pass;
}

sub set_password
{
	my $passwd = shift || return;
	my $tmp = '/var/tmp/bmcinit.'.$$;
	open(FH, "<$init") || die "Cannot open $init : $?\n";
	open(FH2, ">$tmp") || die "Cannot open $tmp : $?\n";

	while(my $line = <FH>) {
		if($line =~ /^(PASSWORD)=(.*)/) {
			print FH2 "PASSWORD=$passwd\n";
		} else { print FH2 $line };

	}
	close(FH);
	close(FH2);
	
	system("/bin/mv $tmp $init");
	system("/bin/chmod 700 $init");
}

sub check_password
{
	my $passwd;
	open(FH, "<$init") || die "Cannot open $init : $?";
	while(my $line = <FH>) {
		if($line =~ /^(PASSWORD)=(.*)/) {
			if($2) { $passwd = $2 }
		}
	}
	close(FH);
			
	return $passwd;
}	

sub enable_startup
{
	my $passwd = shift;
	my $ip = shift;
	my $bmc_cmd = $bmc_bin;

	system("$chkconfig --level 35 bmcscript on");
	system("$init start");
}

sub disable_startup  
{
	system("$chkconfig --level 0123456 bmcscript off");
}

sub usage
{
	print "$0 [OPTIONS] (start|stop)\n";
	print "\t-h help text\n";
	print "\t-P password for the BMC\n";
	print "\tstart - enable the bmc to run at startup\n";
	print "\tstop - disbale the bmc at startup\n";
	print "\n";

	exit 0;
}
