#!/usr/bin/perl
#
# $Revision: 1.4 $
# Copyright 2010 Teleflora
#
# System initialization.
#

use strict;
use warnings;
use Getopt::Long;
use POSIX;
use Digest::MD5;
use File::Basename;


my $CVS_REVISION = '$Revision: 1.4 $';
my $CVS_REV_NR = $CVS_REVISION;
if ($CVS_REVISION =~ /(\$Revision)(: )(\d+\.\d+)( \$)/) {
	$CVS_REV_NR = $3;
}
my $PROGNAME = basename($0);

my $VERSION = 0;
my $INSTALL = 0;
my $HELP = 0;

my $OS = "";
my $TIMEOUT_MENU_ARG = "";
my $TOOLSDIR  = "";


GetOptions(
	"version" => \$VERSION,
	"help" => \$HELP,
);


if($VERSION != 0) {
	print("$PROGNAME: $CVS_REVISION\n");
	exit(0);
}

if($HELP != 0) {
	print("\n");
	print("Teleflora POS Red Hat Enterprise Linux System initialization\n");
	print("Usage:\n");
	print("$PROGNAME\n");
	print("$PROGNAME --help\n");
	print("$PROGNAME --version\n");
	print("\n");
	exit(0);
}


#
# If TERM is unset, dump them to a shell.
#
unless (defined($ENV{'TERM'})) {
	print("The TERM environemnt variable is not defined - please fix.\n");
	print("\n");
	print("execing the Bash Shell...\n");
	exec("/bin/bash");
}

#
# "scoansi-old" emulation works for both the "dialog" and "sshbbx" applications.
#
if($ENV{'TERM'} eq "ansi") {
	$ENV{'TERM'} = "scoansi-old";
}

#
# Set the global variable indicating what OS script is running on.
#
determine_os();

#
# Handle signals.
# Mainly, prevent "breaking out" to a shell.
#
set_signal_handlers('IGNORE');

#
# No need to timeout the menu - PCI does not apply here since this script is only
# run on uninstalled systems.
#
$TIMEOUT_MENU_ARG = "";

my $title = "";
my $command = "";
my $returnval =  "";

logevent("Starting SysInit Menu");

while(1) {
	# Summary information about this shop.
	$title = titlestring("SysInit Menu");
	$title .= "   SysInit Menu Version: $CVS_REV_NR\\n";
	$title .= "      Linux Platform ID: $OS\\n";
	$title .= "\\n";
	$title .= "\\n";

	$command = "dialog --stdout";
	$command .= " $TIMEOUT_MENU_ARG";
	$command .= " --no-cancel";
	$command .= " --default-item \"Exit\"";
	$command .= " --menu '$title'";
	$command .= " 0 0 0";

	$command .= " \"OSTools\"" . " \"Install OSTools Package - FIRST STEP\"";

	$command .= " \"DsySysInit\"" . " \"Daisy Initial System Setup\"";

	$command .= " \"RTISysInit\"" . " \"RTI Initial System Setup\"";

	$command .= " \"CustomizeImage\"" . " \"Customize Image Config\"";

	$command .= " \"Commandline\"" . " \"Go to the Linux Shell\"";

	$command .= " \"About\"" . " \"About Box\"";
	$command .= " \"Doc\"" . " \"Info about use of this script\"";
	$command .= " \"Exit\"" . " \"Exit\"";

	# Redirect stderr to stdout so that we can tell if there was a timeout
	# since 'dialog' writes "timeout" to stderr and exits if a timeout happens.
	$returnval = qx($command 2>&1);

	# Remove trailing and leading newlines because if there was a timeout,
	# the form of the output is:
	#	^\ntimeout\n$
	chomp($returnval);
	$returnval =~ s/^\n//;

	next if (!$returnval);

	if($returnval eq "timeout") {
		logevent("Inactivity Timeout");
		exit(0);

	# Install OSTools Package
	} elsif($returnval eq "OSTools") {
		ostools_main();

	# Initial Daisy System Setup
	} elsif($returnval eq "DsySysInit") {
		dsy_sysinit_main();

	# Initial RTI System Setup
	} elsif($returnval eq "RTISysInit") {
		rti_sysinit_main();

	# Initial Image Setup
	} elsif($returnval eq "CustomizeImage") {
		customize_image_main();

	# Escape to shell
	} elsif($returnval eq "Commandline") {
		system("/usr/bin/clear");
		logevent("Begin Shellout to Commandline.");
		set_signal_handlers('DEFAULT');
		system("PS1=\"\\n\\u\@\\h: \\w\\n\\d \\t \\\$ \" /bin/bash");
		set_signal_handlers('IGNORE');
		logevent("Finish Shellout to Commandline.");

	# About Box
	} elsif($returnval eq "About") {
		sysinit_about();

	# Doc
	} elsif($returnval eq "Doc") {
		sysinit_doc();

	} elsif($returnval eq "Exit") {
		$returnval = menu_confirm("Exit SysInit Menu?", "Yes");
		if($returnval eq "Y") {
			logevent("Finish Support Menu.");
			exit(0);
		}
	}
}

exit(0);

###############################################################################
###############################################################################
###############################################################################


sub ostools_main
{
	$returnval = menu_confirm("Download and Install Teleflora OSTools Package?");
	if($returnval eq "Y") {
		my $ins_script = "install-ostools-1.12.pl";
		my $url = "http://rtihardware.homelinux.com/ostools/$ins_script";
		system("curl -s -o /tmp/$ins_script $url");
		if (-f "/tmp/$ins_script") {
			system("perl /tmp/$ins_script --update");
		}
		wait_for_user();
	}
}


sub customize_image_main
{
	my $command = "";
	my $returnval = "";

	determine_toolsdir();

	my $title = titlestring("Image Init Menu");

	while(1) {

		$command = "dialog --stdout";
		$command .= " --no-cancel";
		$command .= " --default-item \"Close\"";
		$command .= " --menu '$title'";
		$command .= " 0 0 0";

		$command .= " \"Hostname\""       . " \"Set the Hostname\"";
		$command .= " \"Altiris\""        . " \"Install Altiris\"";
		$command .= " \"Redhat License\"" . " \"Get a Redhat License\"";
		$command .= " \"RHNSystemID\""    . " \"Report the Redhat Network System ID\"";
		$command .= " \"Close\""          . " \"Close This Menu\"";

		open(OSDIALOG, "$command |");
		$returnval = <OSDIALOG>;
		close(OSDIALOG);
		next if(! $returnval);
		chomp($returnval);

		if($returnval eq  "timeout") {
			logevent("Inactivity Timeout.");
			exit(0);

		} elsif($returnval eq "Hostname") {
			customize_image_hostname();

		} elsif($returnval eq "Altiris") {
			customize_image_altiris();

		} elsif($returnval eq "Redhat License") {
			customize_image_redhat_license();

		} elsif($returnval eq "RHNSystemID") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --rhnsystemid");
			wait_for_user();

		} elsif($returnval eq "Close") {
			return(0);
		}
	}
}

#
# On Redhat systems, the steps for changing the hostname are:
# 0) get shopcode
# 1) edit /etc/sysconfig/network
# 2) edit /etc/hosts
# 3) run the hostname command
# 4) reboot or at least restart the network service
#
sub customize_image_hostname
{
	my $shopcode = customize_image_shopcode();

	unless ($shopcode) {
		menu_info("Set Hostname Cancelled. No Changes Made.");
		return;
	}

	my $hostname = "$shopcode-tsrvr";;

	unless (customize_image_edit_network_file($hostname)) {
		menu_info("Error Setting Hostname: sysconfig network file.");
		return;
	}

	unless (customize_image_edit_hosts_file($hostname)) {
		menu_info("Error Setting Hostname: hosts file.");
		return;
	}

	system("sudo hostname $hostname");
	if ($? != 0) {
		menu_info("Error Setting Hostname: \"hostname\" command error.");
		return;
	}
}

sub customize_image_altiris
{
	system("/usr/bin/clear");
	system("sudo $TOOLSDIR/bin/altiriscontrol.pl --install");
	wait_for_user();
}

sub customize_image_redhat_license
{
	my $returnval = menu_confirm("Download and Apply Redhat OS Updates Now?");
	if($returnval eq "Y") {
		system("sudo $TOOLSDIR/bin/updateos.pl --ospatches");
		wait_for_user();
	}
}

sub customize_image_shopcode
{
	my $shopcode = menu_getstring("Please enter an 8 digit Shop Code");

	unless ($shopcode) {
		return "";
	}
	unless ($shopcode =~ /^\d{8}$/) {
		menu_info("Shop Code must be 8 digits.");
		return "";
	}

	return($shopcode);
}

sub customize_image_edit_network_file
{
	my $hostname = $_[0];
	my $current_file = "/etc/sysconfig/network";
	my $saved_file = "${current_file}.orig";
	my $tmpfile = "/tmp/tfsupport.sethostname.$$";

	open(OLDFILE, "< $current_file");
	open(NEWFILE, "> $tmpfile");
	while (<OLDFILE>) {
		if(/^(\s*)(HOSTNAME)(\s*)(=)(\s*)(\S+)/) {
			print(NEWFILE "HOSTNAME=$hostname\n");
		} else {
			print(NEWFILE);
		}
	}
	close(OLDFILE);
	close(NEWFILE);

	# measure of success: the generated file contains something
	if (-s $tmpfile > 0) {
		system("sudo mv $current_file $saved_file");
		system("sudo cp $tmpfile $current_file");
		system("sudo chown root:root $current_file");
		system("sudo chmod 644 $current_file");
		system("sudo rm $tmpfile");
	} else {
		menu_info("Error Setting Hostname: generated file empty.");
		system("rm $tmpfile");
		return(0);
	}

	return(1);
}

sub customize_image_edit_hosts_file
{
	my $hostname = $_[0];
	my $current_file = "/etc/hosts";
	my $saved_file = "${current_file}.orig";
	my $tmpfile = "/tmp/tfsupport.sethostname.$$";

	open(OLDFILE, "< $current_file");
	open(NEWFILE, "> $tmpfile");
	while (<OLDFILE>) {
		if (/^127.0.0.1[ \t]+/) {
			print(NEWFILE "127.0.0.1\t$hostname localhost.localdomain localhost\n");
		} else {
			print(NEWFILE);
		}
	}
	close(OLDFILE);
	close(NEWFILE);

	# measure of success: the generated file contains something
	if (-s $tmpfile > 0) {
		system("sudo mv $current_file $saved_file");
		system("sudo cp $tmpfile $current_file");
		system("sudo chown root:root $current_file");
		system("sudo chmod 644 $current_file");
		system("sudo rm $tmpfile");
	} else {
		menu_info("Error Setting Hostname: generated file empty.");
		system("rm $tmpfile");
		return(0);
	}

	return(1);
}

sub dsy_sysinit_main
{
	my $command = "";
	my $returnval = "";

	determine_toolsdir();

	my $title = titlestring("Daisy System Init Menu");

	while(1) {

		$command = "dialog --stdout";
		$command .= " --no-cancel";
		$command .= " --default-item \"Close\"";
		$command .= " --menu '$title'";
		$command .= " 0 0 0";

		$command .= " \"Baremetal\""   . " \"Post Kickstart Install\"";
		$command .= " \"RHNSystemID\"" . " \"Report the Redhat Network System ID\"";
		$command .= " \"OSPatches\""   . " \"Install OS Patches\"";
		$command .= " \"Daisy8\""      . " \"Daisy v8 Install Prep\"";
		$command .= " \"Close\""       . " \"Close This Menu\"";

		open(OSDIALOG, "$command |");
		$returnval = <OSDIALOG>;
		close(OSDIALOG);
		next if(! $returnval);
		chomp($returnval);

		if($returnval eq  "timeout") {
			logevent("Inactivity Timeout.");
			exit(0);

		} elsif($returnval eq "Baremetal") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --baremetal");
			wait_for_user();

		} elsif($returnval eq "RHNSystemID") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --rhnsystemid");
			wait_for_user();

		} elsif($returnval eq "OSPatches") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --ospatches");
			wait_for_user();

		} elsif($returnval eq "Daisy8") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --daisy8");
			wait_for_user();

		} elsif($returnval eq "Close") {
			return(0);
		}
	}
}

sub rti_sysinit_main
{
	my $command = "";
	my $returnval = "";

	determine_toolsdir();

	my $title = titlestring("RTI System Init Menu");

	while(1) {

		$command = "dialog --stdout";
		$command .= " --no-cancel";
		$command .= " --default-item \"Close\"";
		$command .= " --menu '$title'";
		$command .= " 0 0 0";

		$command .= " \"Hostname\""    . " \"Set Hostname\"";
		$command .= " \"TimeZone\""    . " \"Set Time Zone\"";
		$command .= " \"OSTools\""     . " \"Install OSTools Package\"";
		$command .= " \"Baremetal\""   . " \"Post Kickstart Install\"";
		$command .= " \"RHNSystemID\"" . " \"Report the Redhat Network System ID\"";
		$command .= " \"OSPatches\""   . " \"Install OS Patches\"";
		$command .= " \"RTI12\""       . " \"Install RTI v12\"";
		$command .= " \"RTI14\""       . " \"Install RTI v14\"";
		$command .= " \"SSHKeys\""     . " \"Configure SSH Keys\"";
		$command .= " \"SambaPW\""     . " \"Configure Samba Passwords\"";
		$command .= " \"DRAC\""        . " \"Configure DRAC\"";
		$command .= " \"DSET\""        . " \"Install DSET\"";
		$command .= " \"TestBU\""      . " \"Test Backup\"";
		$command .= " \"TmpCleanup\""  . " \"/tmp Cleanup\"";
		$command .= " \"Network\""     . " \"Network Restart\"";
		$command .= " \"Reboot\""      . " \"Reboot System\"";
		$command .= " \"Shell\""       . " \"Go to the Linux Shell\"";
		$command .= " \"Close\""       . " \"Close This Menu\"";

		open(OSDIALOG, "$command |");
		$returnval = <OSDIALOG>;
		close(OSDIALOG);
		next if(! $returnval);
		chomp($returnval);

		if($returnval eq  "timeout") {
			logevent("Inactivity Timeout.");
			exit(0);

		} elsif($returnval eq "Hostname") {
			rti_sysinit_hostname();
			wait_for_user();

		} elsif($returnval eq "TimeZone") {
			rti_sysinit_timezone();
			wait_for_user();

		} elsif($returnval eq "OSTools") {
			ostools_main();

		} elsif($returnval eq "Baremetal") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --baremetal");
			wait_for_user();

		} elsif($returnval eq "RHNSystemID") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --rhnsystemid");
			wait_for_user();

		} elsif($returnval eq "OSPatches") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --ospatches");
			wait_for_user();

		} elsif($returnval eq "RTI12") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --rti12 --tfserver=192.168.1.51");
			wait_for_user();

		} elsif($returnval eq "RTI14") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --rti14 --tfserver=192.168.1.51");
			wait_for_user();

		} elsif($returnval eq "SSHKeys") {
			system("/usr/bin/clear");
			rti_sysinit_sshkeys();
			wait_for_user();

		} elsif($returnval eq "SambaPW") {
			system("/usr/bin/clear");
			rti_sysinit_sambapw();
			wait_for_user();

		} elsif($returnval eq "DRAC") {
			system("/usr/bin/clear");
			rti_sysinit_drac();
			wait_for_user();

		} elsif($returnval eq "DSET") {
			system("/usr/bin/clear");
			rti_sysinit_dset();
			wait_for_user();

		} elsif($returnval eq "TestBU") {
			system("/usr/bin/clear");
			rti_sysinit_testbu();
			wait_for_user();

		} elsif($returnval eq "TmpCleanup") {
			system("/usr/bin/clear");
			rti_sysinit_tmp_cleanup();
			wait_for_user();

		} elsif($returnval eq "Network") {
			system("/usr/bin/clear");
			system("/sbin/service network restart");
			wait_for_user();

		} elsif($returnval eq "Reboot") {
			system("/usr/bin/clear");
			system("$TOOLSDIR/bin/updateos.pl --reboot");
			wait_for_user();

		} elsif($returnval eq "Shell") {
			system("/usr/bin/clear");
			logevent("Begin Shellout to Commandline.");
			set_signal_handlers('DEFAULT');
			system("PS1=\"\\n\\u\@\\h: \\w\\n\\d \\t \\\$ \" /bin/bash");
			set_signal_handlers('IGNORE');
			logevent("Finish Shellout to Commandline.");

		} elsif($returnval eq "Close") {
			return(0);
		}
	}
}

sub rti_sysinit_hostname
{
	my $hostname = qx(hostname);

	unless ($hostname) {
		menu_info("Error setting hostname: can't get current hostname");
		return("");
	}

	$hostname = menu_getstring("Enter New Hostname (Currently $hostname)");

	unless ($hostname) {
		menu_info("Set Hostname Cancelled. No Changes Made.");
		return("");
	}

	system("$TOOLSDIR/bin/updateos.pl --hostname=$hostname");

	return($hostname);
}

sub rti_sysinit_timezone
{
	system("/usr/bin/setup");
}

sub rti_sysinit_sshkeys
{
}

sub rti_sysinit_sambapw
{
}

sub rti_sysinit_drac
{
}

sub rti_sysinit_dset
{
}

sub rti_sysinit_testbu
{
}

sub rti_sysinit_tmp_cleanup
{
}

sub sysinit_about
{
	system("/usr/bin/clear");
	print << "EOF";
tfsysinit.pl, $CVS_REVISION

The Teleflora POS Red Hat Enterprise Linux System Initialization Script

Copyright (c) 2010 Teleflora

Managed Services Group
Linux Technology Dept

Tip o' the hat to:
	Larry Wall
	Linux Torvolds
	Red Hat, Inc
	Dell, Inc
EOF
	wait_for_user();
}

sub sysinit_doc
{
	system("pod2text $0 | less");
}


#
# Where is the OSTools package?
# Ultimately, ostools should reside under either:
# /d/ostools/bin/ /usr2/ostools/bin/ or /teleflora/ostools/bin/
#
sub determine_toolsdir
{
	if (-d "/d") {
		$TOOLSDIR="/d/ostools";
	} elsif (-d "/usr2") {
		$TOOLSDIR="/usr2/ostools";
	} elsif (-d "/teleflora") {
		$TOOLSDIR="/teleflora/ostools";
	} else {
		# At this point, none of the expected dirs exist, so use the default.
		$TOOLSDIR="/teleflora/ostools";
	}
}


sub menu_confirm
{
	my $title = $_[0];
	my $default = $_[1];
	my $command = "";


	$command = "dialog --stdout";
	$command .= " $TIMEOUT_MENU_ARG";
	if( ($default) && ($default =~ /^no$/i)) {
		$command .= " --defaultno";
	}
	$command .= " --yesno";
	$command .= " \"$title\"";
	$command .= " 0 0";

	system("$command");

	if($? == 0) {
		return("Y");

	} elsif ($? == 255) {
		# Timeout
		logevent("Inactivity Timeout.");
		exit(0);
		
	} else {
		return("N");
	}
}


sub menu_info
{
	my $title = $_[0];
	my $command = "";


	$command = "dialog --stdout";
	$command .= " $TIMEOUT_MENU_ARG";
	$command .= " --msgbox";
	$command .= " \"$title\"";
	$command .= " 7 50";

	system("$command");
	if($? == 255) {
		# Timeout
		logevent("Inactivity Timeout.");
		exit(0);
	}

	return(0);
}


sub menu_getstring
{
	my $title = $_[0];
	my $default = $_[1];
	my $command = "";
	my $returnval = "";

	$command = "dialog --stdout";
	$command .= " $TIMEOUT_MENU_ARG";
	$command .= " --no-cancel";
	$command .= " --inputbox '$title'";
	$command .= " 0 0";
	if( ($default) && ("$default" ne "")) {
		$command .= " \"$default\"";
	}



	open(DIALOG, "$command |");
	$returnval = <DIALOG>;
	close(DIALOG);

	unless (defined $returnval) {
		return("");
	}

	chomp($returnval);
	
	$returnval = validate_input($returnval);

	if($returnval eq "timeout") {
		# Timeout
		logevent("Inactivity Timeout.");
		exit(0);
	}

	return("$returnval");
}


#
# Simple radio button box.
#
sub menu_pickone
{
	my $title = $_[0];
	my %options = %{$_[1]};
	my $default = $_[2];
	my $key = "";
	my $value = "";


	my $command = "";
	my $returnval = "";

	$command = "dialog --stdout";
	$command .= " $TIMEOUT_MENU_ARG";
	# $command .= " --no-cancel";
	$command .= " --radiolist '$title' 0 0 0 ";
	foreach $key (sort(keys(%options))) {
		$value = $options{$key};
		$command .= " " . "\"$key\" \"$value\" ";
		if("$key" eq "$default") {
			$command .= " on";
		} else {
			$command .= " off";
		}
	}


	open(DIALOG, "$command |");
	$returnval = <DIALOG>;
	close(DIALOG);
	return if(! $returnval);
	chomp($returnval);
	
	$returnval = validate_input($returnval);

	if($returnval eq "timeout") {
		# Timeout
		logevent("Inactivity Timeout.");
		exit(0);
	}

	return("$returnval");
}


sub titlestring
{
	my $title = $_[0];
	my $returnval = "";

	$returnval = "--------======== $title =======---------\\n";
	
	# Get our hostname.
	#$returnval .= get_hostname("--short");
	#$returnval .= " - ";

	# Current timestamp.
	$returnval .= strftime("%a %B %d, %Y %T %Z", localtime());
	$returnval .= "\\n";
	$returnval .= "\\n";



	return($returnval);
}




sub viewfiles
{
	my $filepattern = $_[0];
	my $sudo = $_[1];
	my $filter = $_[2];
	my @files = ();
	my $file = "";
	my $lasttype = "";
	my $command = "";


	if((! $filepattern) || ("$filepattern" eq "")) {
		return("");
	}


	if (($sudo) && ("$sudo" ne "")) {
		$sudo = "sudo ";
	} else {
		$sudo = "";
	}

	if(! $filter) {
		$filter = "";
	}


	if("$sudo" ne "") {
		open(FILELIST, "sudo /bin/ls -t $filepattern |");
	} else {
		open(FILELIST, "/bin/ls -t $filepattern |");
	}
	while(<FILELIST>) {
		chomp;
		push(@files, $_);
	}
	close(FILELIST);





	$command = "(/bin/true";
	$lasttype = "";
	foreach $file(@files) {

		if($file =~ /\.gz$/) {
			$command .= " ; $sudo /bin/zcat $file | tac";
		} else {
			$command .= " ; $sudo /usr/bin/tac $file";
		}
	}
	$command .= ") ";
	if($filter ne "") {
		$command .= " | $filter";
	}
	system("$command | less");

	# Return the command... without trailing "| less"
	# This allow our caller to re-run the command and, print results to a printer
	# (Especially useful for security logs.)
	return($command);
}


sub get_linux_version
{
	my $linux_version = qx(cat /etc/redhat-release);

	chomp($linux_version);

	return($linux_version);
}



# Get our hostname.
sub get_hostname
{
	my $hostname_type = $_[0];
	my $returnval = "";

	open(HOST, "/bin/hostname $hostname_type |");
	while(<HOST>) {
		chomp;
		if ($_ ne "") {
			$returnval = $_;
			last;
		}
	}
	close(HOST);

	return ($returnval);
}


#
# Sets global variable $OS to one of:
#	RH72
#	FC3
#	FC4
#	FC5
#	RHEL4
#	RHEL5

sub determine_os
{
	$OS = "";

	# We could also use /usr/bin/lsb-release
	open(FILE, "< /etc/redhat-release");
	while(<FILE>) {

		# Fedora Core 3
		if(/(Fedora)(\s+)(Core)(\s+)(release)(\s+)(3)/) {
			$OS = "FC3";
			last;
		}

		# Fedora Core 4
		if(/(Fedora)(\s+)(Core)(\s+)(release)(\s+)(4)/) {
			$OS = "FC4";
			last;
		}

		# Fedora Core 5
		if(/(Fedora)(\s+)(Core)(\s+)(release)(\s+)(5)/) {
			$OS = "FC5";
			last;
		}

		# EL 5
		if( (/(release)(\s+)(5)/)
		||  (/(CentOS)([[:print:]]+)(\s)(5)/) ) {
			$OS = "RHEL5";
			last;
		}

		# EL 4
		if( (/(release)(\s+)(4)/) 
		||  (/(CentOS)([[:print:]]+)(\s)(4)/) ) {
			$OS = "RHEL4";
			last;
		}

		# ES 3
		if( /(release)(\s+)(3)/ ) {
			$OS = "RHEL3";
			last;
		}

		# Redhat 7.2
		if(/(release)(\s+)(7\.2)/) {
			$OS = "RH72";
			last;
		}
	}
	close(FILE);
}


# trim whitespace from start and end of string
sub trim
{
	my $string = $_[0];

	$string =~ s/^\s+//;
	$string =~ s/\s+$//;

	return $string;
}
# trim leading whitespace
sub ltrim
{
	my $string = $_[0];

	$string =~ s/^\s+//;

        return $string;
}
# trim trailing whitespace
sub rtrim
{
        my $string = $_[0];

        $string =~ s/\s+$//;

        return $string;
}

sub system_exit_status
{
        my $exit_status = $_[0];
        my $strerror = "";

        if ($exit_status == -1) {
                $strerror = "system() failed to execute: $!";
        } elsif ($exit_status & 127) {
                my $signalnr = ($exit_status & 127);
                $strerror = "system() died from signal: $signalnr";
        } else {
                my $return_status = ($exit_status >> 8);
                if ($return_status) {
                        $strerror = "system() exited with value: $return_status";
                }
        }

        return $strerror;
}

#
# User presses enter to clear input of a screen.
#
sub wait_for_user
{
	my $temp = "";

	print("\nPress the Enter key to continue ...");
	$temp = <STDIN>;
	return(0);
}


# PCI 6.5.6
# "some string; `cat /etc/passwd`" -> "some string cat /etc/passwd"
# "`echo $ENV; $(sudo ls)`" -> "echo ENV sudo ls"
# etc.
sub validate_input
{
	my $var = $_[0];
	my $temp = "";

	if(! $var) {
		return "";
	}

	$temp = $var;

	# "`bad command`" -> "bad command"
	$temp =~ s/\`//g;

	# "$(bad command)" -> "bad command"
	$temp =~ s/(\$\()(.*.)(\))/$2/g;


	# "stuff ; bad command" -> "stuff bad command"
	$temp =~ s/\;//g;

	# "stuff && bad command" -> "stuff bad command"
	$temp =~ s/\&//g;

	# "stuff | bad command" -> "stuff bad command"
	$temp =~ s/\|//g;

	# "stuff > bad command" -> "stuff bad command"
	$temp =~ s/\>//g;

	# "stuff < bad command" -> "stuff bad command"
	$temp =~ s/\<//g;

	# Filter non printables
	$temp =~ s/[[:cntrl:]]//g;


	return($temp);
}


sub set_signal_handlers
{
	my $handler = $_[0];

	$SIG{'STOP'} = $handler;
	$SIG{'TSTP'} = $handler;
	$SIG{'INT'} = $handler;
}


#
# Send an event to syslog.
#
sub logevent
{
	my $event = $_[0];
	my $logger = "";
	my $user =  "";
	my $client = "";

	if(-f "/bin/logger") {
		$logger = "/bin/logger";
	} elsif(-f "/usr/bin/logger") {
		$logger = "/usr/bin/logger";
	} else {
		# Hope for the best.
		$logger = "logger";
	}

	if(defined $ENV{'USER'}) {
		$user = $ENV{'USER'};
	}
	if(defined $ENV{'SSH_CLIENT'}) {
		$client = $ENV{'SSH_CLIENT'};
	} else {
		open(TTY, "/usr/bin/tty |");
		while(<TTY>) {
			chomp;
			$client = $_;
			last;
		}
		close(TTY);
	}

	system("$logger \"(PID $$: $user\@$client) $event\"");
	print("$event\n");
}

__END__

=head1 NAME

tfsysinit.pl - Teleflora POS RHEL System Initialization Script

=head1 SYNOPSIS

tfsysinit.pl

tfsysinit.pl B<--version>

tfsysinit.pl B<--help>

=head1 OPTIONS

=over 4

=item B<--version>

Output the version number of the script and exit.

=item B<--help>

Output a short help message and exit.

=back

=head1 DESCRIPTION

The B<tfsysinit.pl> script provides a convenient way to initialize a
Teleflora POS system after a kickstart install of the 
Red Hat Enterprise Linux operating system or
a restore of a Clonezilla image of a POS system.

=over 4

=item OSTools

This is always the first step of installation after a kickstart install
of the operating system.  It installs the lastest version of the
OSTools package and is done before installing any POS specific software.

=back

=over 4

=item DsySysInit

Initialize a Daisy server after the RHEL 5.5 Server 32-bit operating system
has been installed via the kickstart file.

Major steps:

=over 4

=item 1.

"Baremetal": Do a "baremetal" post-install.
This step registers with the server with the Redhat Network,
installs required software packages, edits config files, and
install all applicable hardware patches.

=item 2.

"RHNSystemID": Verify that a Redhat Network system ID was obtained
in the "OSPatches" step.

=item 3.

"OSPatches": Install all applicable operating system pataches available
from the Redhat Network.  The server must be currently registered with
the Redhat Network and have a system id.

=item 4.

"Daisy8: Perform the post-install configuration for a Daisy server.
Steps include setting the IP address of the server to the standard
value of 192.168.1.21, added mount points required by the Daisy
software, configuring the "Samba" file sharing service, and
making the required Daisy user accounts.

=back

=item RTISysInit

Initialize a RIT server after the RHEL 5.5 Server 64-bit operating system
has been installed via the kickstart file.

Major steps:

=over 4

=item 1.

"Hostname": Set the server hostname.

=item 2.

"TimeZone": Set the server time zone.  This is the time zone for the delivery
address of the server.

=item 3.

"OSTools": Install the latest version of the OSTools Package.

=item 4.

"Baremetal": Do a "baremetal" post-install.
This step registers with the server with the Redhat Network,
installs required software packages, edits config files, and
install all applicable hardware patches.

=item 5.

"RHNSystemID": Verify that a Redhat Network system ID was obtained
in the "OSPatches" step.

=item 6.

"OSPatches": Install all applicable operating system pataches available
from the Redhat Network.  The server must be currently registered with
the Redhat Network and have a system id.

=item 7.

"RTI12": Install RTI v12.

=item 8.

"RTI14": Install RTI v14.

=item 9.

"SSHKeys" Configure SSH keys.

=item 10.

"SambaPW": Configure Samba passwords.

=item 11.

"DRAC": Configure DRAC.

=item 12.

"DSET": Install DSET.

=item 13.

"TestBU": Test backup.

=item 14.

"TmpCleanup": Cleanup files in C</tmp>.

=item 15.

"Network": Restart the network interface.

=item 16.

"Reboot" Reboot the server.

=back


=item ImageInit

Initialize a system after a "clonezilla" install.

Major steps in order:

=over 4

=item 1.

"Hostname": Set the server hostname.
You will be asked to supply the florist's shopcode
since the hostname is formed from by concatenating the shopcode with
the suffix "-tsrvr".

=item 2.

"Altiris": Install Altiris.

=item 3.

"Redhat License": Obtain a new Red Hat License

=item 4.

"RHNSystemID": Report the Redhat Network System ID, to
verify that a Redhat Network system ID was obtained
in the "Redhat License" step.

=back

=back

=head1 FILES

=head1 DIAGNOSTICS

=head1 SEE ALSO

tfsupport.pl, updateos.pl, dialog(1)

=cut
