#!/usr/bin/perl
###############
# RHN Registration System
$Version="0.1.22";
##############
use strict;
use vars qw/$Version $DEBUG $SILENT $API_HOST $API_URL $RHN_ORG_CERT_RPM $GPG_KEY_URL/;
use LWP::UserAgent;
use Getopt::Std;
use Term::ReadKey;
$API_HOST='api.rhn.rackspace.com';
$API_URL='https://' . $API_HOST . '/cgi-bin/api/api.cgi';
$GPG_KEY_URL='https://rax.mirror.rackspace.com/el/keys/keybundle';
$RHN_ORG_CERT_RPM='https://rax.mirror.rackspace.com/el/carpms/rhn-org-trusted-ssl-cert-1.0-1.noarch.rpm';

&Parse_Switches;

#####

sub Parse_Switches
{
my ($available_options,%OPTIONS);
$available_options = "dhmnNop:rsS:tu:v";
getopts($available_options, \%OPTIONS)||&Usage;
&Usage() if $OPTIONS{'h'};
&Version() if $OPTIONS{'v'};
$DEBUG=1 if $OPTIONS{'d'};
$SILENT=1 if $OPTIONS{'s'};
&Register($OPTIONS{'u'},$OPTIONS{'p'},'',$OPTIONS{'S'},$OPTIONS{'N'}) if $OPTIONS{'n'};
&ReRegister($OPTIONS{'u'},$OPTIONS{'p'},'',$OPTIONS{'S'},$OPTIONS{'N'}) if $OPTIONS{'r'};

if(!%OPTIONS){&Usage;}
exit 0;
}

##

sub ReRegister
{
my $username=shift;
my $password=shift;
my $old=shift;
my $server_number=shift;
my $SKIPUPDATE=shift;
my $Proxy=$ENV{'http_proxy'};
$Proxy=~s/^https?:\/\///;
if(!-e "/usr/sbin/rhnreg_ks")
	{
	print "Required software, rhnreg_ks, not installed.\n";
	exit 1;
	}
if(-e "/etc/NCCcredentials")
	{
	unlink("/etc/NCCcredentials");
	}
if(!$server_number){$server_number=&Get_Server_Number;}
if($server_number !~ /^[0-9]+$/){&Error("Invalid server number, $server_number");}
if(!$username)
	{
	print "SSO Username: ";
	$username=<STDIN>;
	chomp($username);
	}
if(!$password)
	{
	print "One Time Password: ";
	ReadMode('noecho');
	$password=ReadLine(0);
	chomp($password);
	ReadMode('normal');
	print "\n";
	}
if(!$SILENT)
	{
	print "Is this the correct server number, $server_number? [Y,n] ";
	my $answer=<STDIN>;
	chomp($answer);
	if(!$answer){$answer="Y";}
	if(lc $answer ne "y"){exit 1;}
	print "This will remove any existing registrations for server, $server_number, do you want to proceed? [y/N] ";
	my $answer=<STDIN>;
	chomp($answer);
	if(lc $answer ne "y"){exit 1;}
	}
my $content="";
my $registration="";
my $update="";
my $failed="";
my $osad="";
#my $rpmtest=qx|rpm -q subscription-manager|;
#chomp($rpmtest);
#if($rpmtest ne "package subscription-manager is not installed")
#	{
#	if($DEBUG){print "Removing subscription manager\n";}
#	qx|yum --disableplugin=rhn -y remove subscription-manager|;
#	}
&Add_GPG_Keys;

my $ua=LWP::UserAgent->new;
$ua->agent("rs-tools/$Version");
$ua->credentials("$API_HOST:443",'RHN Registration System',$username,$password);
if($DEBUG)
	{
	print "Obtaining activation key from API server\n";
	$content=$ua->get("$API_URL?device=$server_number&new=0&old=$old&debug=1");
	print $content->decoded_content."\n";
	}
else
	{
	$content=$ua->get("$API_URL?device=$server_number&new=0&old=$old");
	}
if($content->status_line =~ /401 Authorization Required/)
	{
	print "Authentication failure\n";
	exit 1;
	}
if($content->status_line !~ /^200 OK$/)
	{
	print "Connection error to API server.\n";
	exit 1;
	}
my @info=split("\n",$content->decoded_content);
foreach(@info)
	{
	if(/^\/usr\/sbin\/rhnreg_ks/){$registration=$_;}
	chomp($registration);
	if(/^\/usr\/bin\/yum/){$update=$_;}
	chomp($update);
	if(/^Unsupported OS for registration/)
		{
		print STDERR "This OS is not available to register\n";
		exit;
		}
	if(/chkconfig osad/){$osad=$_;}
	chomp($osad);
	}
if($Proxy){$registration.=" --proxy=$Proxy";}
if($DEBUG){print "registration command: $registration\n";}
sleep(5);
if(!$SILENT){print "Registering system\n";}
if($DEBUG)
	{
	open(FILE,"|$registration -v");
	while(<FILE>){print $_;}
	close(FILE);
	my $exit=$?;
	if($exit > 0){print STDERR "registration failed";exit 1;}
	}
else{ qx|$registration|;
	my $exit=$?;
	if($exit > 0){print STDERR "registration failed";exit 1;}}
if(!$SILENT)
	{
	open(FILE,"|yum repolist");
	while(<FILE>){print $_;}
	close(FILE);
	print "Are these the channels you expected from this registration? [Y,n] ";
	my $answer=<STDIN>;
	chomp($answer);
	if(!$answer){$answer="Y";}
	if(lc $answer ne "y")
		{
		print "Please update the sku's in core and re run the registration script\n";
		exit 1;
		}
	}
elsif($DEBUG)
	{
	open(FILE,"yum repolist");
	while(<FILE>){print $_;}
	close(FILE);	
	}
if((!$SILENT)&&(!$SKIPUPDATE))
	{
	print "Do you want to update the system? [Y/n] ";
	my $answer=<STDIN>;
	chomp($answer);
	if(!$answer){$answer="Y";}
	if(lc $answer eq "y")
		{
#		if($DEBUG)
#			{
			open(FILE,"|yum -y update");
			while(<FILE>){print $_;}
			close(FILE);
#			}
#		else{ qx|yum -y update|;}
		}
	}
elsif(($DEBUG)&&(!$SKIPUPDATE))
	{
	open(FILE,"|yum -y update");
	while(<FILE>){print $_;}
	close(FILE);
	}
elsif(!$SKIPUPDATE)
	{ qx|yum -y update|;}
if($osad)
	{
	sleep(5);
	if((!$SILENT)||($DEBUG))
		{
		print "Setting up osad\n";
		}
	qx|$osad|;
	}
if((!$SILENT)||($DEBUG)){print "Congratulations the system is registered\n";}
exit;
}

##

sub Register
{
my $username=shift;
my $password=shift;
my $old=shift;
my $server_number=shift;
my $SKIPUPDATE=shift;
my $Proxy=$ENV{'http_proxy'};
$Proxy=~s/^https?:\/\///;
if(!-e "/usr/sbin/rhnreg_ks")
	{
	print "Required software, rhnreg_ks, not installed.\n";
	exit 1;
	}
if(-e "/etc/NCCcredentials")
	{
	unlink("/etc/NCCcredentials");
	}
if(!$server_number){$server_number=&Get_Server_Number;}
if($server_number !~ /^[0-9]+$/){&Error("Invalid server number, $server_number");}
if(!$username)
	{
	print "SSO Username: ";
	$username=<STDIN>;
	chomp($username);
	}
if(!$password)
	{
	print "One Time Password: ";
	ReadMode('noecho');
	$password=ReadLine(0);
	chomp($password);
	ReadMode('normal');
	print "\n";
	}
if(!$SILENT)
	{
	print "Is this the correct server number, $server_number? [Y,n] ";
	my $answer=<STDIN>;
	chomp($answer);
	if(!$answer){$answer="Y";}
	if(lc $answer ne "y"){exit 1;}
	print "This will remove any existing registrations for server, $server_number, do you want to proceed? [y/N] ";
	my $answer=<STDIN>;
	chomp($answer);
	if(lc $answer ne "y"){exit 1;}
	}
my $content="";
my $registration="";
my $update="";
my $osad="";
#my $rpmtest=qx|rpm -q subscription-manager|;
#chomp($rpmtest);
#if($rpmtest ne "package subscription-manager is not installed")
#	{
#	if($DEBUG){print "Removing subscription manager\n";}
#	qx|yum --disableplugin=rhn -y remove subscription-manager|;
#	}
&Add_GPG_Keys;

my $ua=LWP::UserAgent->new;
$ua->agent("rs-tools/$Version");
$ua->credentials("$API_HOST:443",'RHN Registration System',$username,$password);
if($DEBUG)
	{
	print "Obtaining activation key from API server\n";
	$content=$ua->get("$API_URL?device=$server_number&new=1&old=$old&debug=1");
	print $content->decoded_content."\n";
	}
else
	{
	$content=$ua->get("$API_URL?device=$server_number&new=1&old=$old");
	}
if($content->status_line =~ /401 Authorization Required/)
	{
	print "Authentication failure\n";
	exit 1;
	}
if($content->status_line !~ /^200 OK$/)
	{
	print "Connection error to API server.\n";
	exit 1;
	}
my @info=split("\n",$content->decoded_content);
foreach(@info)
	{
	if(/^\/usr\/sbin\/rhnreg_ks/){$registration=$_;}
	chomp($registration);
	if(/^\/usr\/bin\/yum/){$update=$_;}
	chomp($update);
	if(/^Unsupported OS for registration/)
		{
		print STDERR "This OS is not available to register\n";
		exit 1;
		}
	if(/chkconfig osad/){$osad=$_;}
	chomp($osad);
	}
if($Proxy){$registration.=" --proxy=$Proxy";}
if($DEBUG){print "registration command: $registration\n";}
sleep(5);
if(!$SILENT){print "Registering system\n";}
if($DEBUG)
	{
	open(FILE,"|$registration -v");
	while(<FILE>){print $_;}
	close(FILE);
	my $exit=$?;
	if($exit > 0){print STDERR "registration failed";exit 1;}
	}
else{ qx|$registration|;
	my $exit=$?;
	if($exit > 0){print STDERR "registration failed";exit 1;}}
if(!$SILENT)
	{
	open(FILE,"|yum repolist");
	while(<FILE>){print $_;}
	close(FILE);
	print "Are these the channels you expected from this registration? [Y,n] ";
	my $answer=<STDIN>;
	chomp($answer);
	if(!$answer){$answer="Y";}
	if(lc $answer ne "y")
		{
		print "Please update the sku's in core and re run the registration script\n";
		exit 1;
		}
	}
elsif($DEBUG)
	{
	open(FILE,"yum repolist");
	while(<FILE>){print $_;}
	close(FILE);	
	}
if((!$SILENT)&&(!$SKIPUPDATE))
	{
	print "Do you want to update the system? [Y/n] ";
	my $answer=<STDIN>;
	chomp($answer);
	if(!$answer){$answer="Y";}
	if(lc $answer eq "y")
		{
		if($DEBUG)
			{
			open(FILE,"|yum -y update");
			while(<FILE>){print $_;}
			close(FILE);
			}
		else{ qx|yum -y update|;}
		}
#work around for activation key failure
	if($update ne "/usr/bin/yum -y install ")
		{
		print "Installing required packages for SLA/Segment.\n";
		if($DEBUG)
			{
			open(FILE,"|$update");
			while(<FILE>){print $_;}
			close(FILE);
			}
		else{ qx|$update|;}
		}
##work around for activation key failure
#	qx|yum -y install rhncfg rhncfg-client rhncfg-actions|;
	qx|rhn-actions-control --enable-all|;
	qx|rhncfg-client get|;
##
	}
else
	{
	if(($DEBUG)&&(!$SKIPUPDATE))
		{
		open(FILE,"|yum -y update --disableexcludes=all");
		while(<FILE>){print $_;}
		close(FILE);
		}
	elsif(!$SKIPUPDATE)
		{ qx|yum -y update|;}
	if($DEBUG)
		{
		if($update ne "/usr/bin/yum -y install ")
			{
			print "Installing required packages for SLA/Segment.\n";
			open(FILE,"|$update");
			while(<FILE>){print $_;}
			close(FILE);
			print "Pulling down configuration files.\n";
##work around for activation key failure
#		qx|yum -y install rhncfg rhncfg-client rhncfg-actions|;
			qx|rhn-actions-control --enable-all|;
			open(FILE,"|rhncfg-client get");
			while(<FILE>){print $_;}
			close(FILE);
			}
##
		}
	else
		{
##work around for activation key failure
		if($update ne "/usr/bin/yum -y install ")
			{
			qx|$update|;
#		qx|yum -y install rhncfg rhncfg-client rhncfg-actions|;
			qx|rhn-actions-control --enable-all|;
			qx|rhncfg-client get|;
			}
##
		}
	}
if($osad)
	{
	sleep(5);
	if((!$SILENT)||($DEBUG))
		{
		print "Setting up osad\n";
		}
	qx|$osad|;
	}
if((!$SILENT)||($DEBUG)){print "Congratulations the system is registered\n";}
exit;
}

##

sub Get_Server_Number
{
my $server_number="";
if(!-e "/root/.rackspace/server_number")
	{
	print "Unable to obtain the server number, please enter the server number: ";
	$server_number=<STDIN>;
	chomp($server_number);
	}
else
	{
	open(FILE,"/root/.rackspace/server_number");
	$server_number=<FILE>;
	close(FILE);
	if($server_number !~ /^[0-9]+/)
		{
		if(!$SILENT)
			{
			print "Invalid server number in /root/.rackspace/server_number, $server_number\n";
			print "Please enter the server number: ";
			$server_number=<STDIN>;
			chomp($server_number);
			}
		else{exit 1;}
		}
	}
chomp($server_number);
return $server_number;
}

##

sub Error
{
my $error=shift;
print "$error\n";
exit 1;
}

##

sub Usage
{
print qq(Usage: rs-tools [OPTION]
Example: rs-tools -v

Available options:
  -d					enable debugging
  -h					show this help message
  -n					invoke a new registration
  -N					do not automatically update packages
  -p					password
  -r					invoke a re-registration (no package/config file installs)
  -s					silent execution (good for automation)
  -S					specify server number instead of read from file
  -u					username
  -v					version information
);
exit 1;
}

##

sub Version
{
print "rs-tools version $Version\n";
exit;
}

##

# Import GPG keys
sub Add_GPG_Keys
{
if (! -e "/usr/share/rhn/RHN-ORG-TRUSTED-SSL-CERT")
	{
	if($DEBUG){print 'Installing RHN organization certificate... ';}
	qx|yum -y localinstall $RHN_ORG_CERT_RPM|;
	if($DEBUG){print qq|Done.\n|;}
	}

if($DEBUG){print 'Importing package signing keys... ';}
qx|rpm --import $GPG_KEY_URL|;
if($DEBUG){print qq|Done.\n|;}
}

##

=head1 NAME

rs-tools - Command line tools for server interactions with RHN registrations and channels

=head1 SYNOPSYS

rs-tools [OPTION]

=head1 DESCRIPTION

This is a program for managing registration with the RHN infrastructure.

=head1 OPTIONS

=over

=item -d			enable debugging

=item -h			show the help message

=item -n			invoke a new registration (includes config files and packages)

=item -N			do not automatically update packages

=item -p			specify a password instead of being prompted

=item -r			invoke a re-registration (no config files or packages)

=item -s			silent execution (good for automation)

=item -S			specify a server number instead of read from file

=item -u			specify a username instead of being prompted

=item -v			version information

=back

=head1 AUTHORS

=over

=item Carl Thompson <carl.thompson@rackspace.com>

=item Herb Jackson <herb.jackson@rackspace.com>

=back

=cut
