#!/usr/bin/perl
#
# InteractiveBastille.pl [ -x | -c ]
#
#   -x	Use the Tk interface
#   -c	Use the Curses interface (default)
#
#
#
# These new modifications were made in Bastille 1.2.0, starting in February 
# of 2001, by Jay Beale.  Tk-specific code is maintained solely by Paul,
# while the remainder is generally maintained by Jay and worked on by
# Jay, Pete Watkins and Paul.
#
#
# The new modifications implement "requirements" so that non-applicable
# questions aren't asked.  Thanks to Lee Brotzman here.  
#
# When we want to skip a question, if YES_CHILD is equal to NO_CHILD, we
# simply go to YES_CHILD.  When they are not equal, we skip to SKIP_CHILD.
#
# The new tags are in implemented in Questions.txt like this:
#
#	REQUIRE_IS_SUID     - question isn't asked if file isn't Set-UID
#	REQUIRE_FILE_EXISTS - question isn't asked if file doesn't exists
#	REQUIRE_DISTRO	    - question isn't asked if distro isn't foo
#
# Each of these are read into the corresponding 
# $Question{question_name}{tag} entry.
#
# The argument list for the first two are lists of files, rather hash entries 
# in $GLOBAL_FILE{}.  The argument for the last is a list of  distributions
# that this question applies to, in the same format as found in API.pm.
#
#
########################################################################
#
# This version of the Bastille 1.1.1 InteractiveBastille.pl script was
# modified by Paul Allen in early December, 2000.  The modifications
# allow the "plugging in" of user interface modules.  
#
# Changes in this file:
#
#  The original Curses interface code has been moved into the module 
#  Bastille_Curses.pm.  If InteractiveBastille.pl is invoked without
#  arguments, the Curses module is used.
#
#  A new module Bastille_Tk.pm has been created to implement a perl/Tk
#  user interface.  If InteractiveBastille.pl is invoked with the
#  switch "-x", the Tk module is used.  For consistency, a "-c"
#  switch selects the Curses module. The script defaults to using the
#  Tk interface if you seem to be running X (if $DISPLAY is set)
#  and have Perl/Tk installed.
#
#  Most of the main-line logic of this file has moved out into the
#  do_Bastille function provided by the user interface modules.  The
#  main-line logic now simply loads the appropriate interface module
#  and calls its do_Bastille function.  The remainder of this file
#  consists of functions not related to the user interface.
#
#  There is now a Populate_Answers function here that can be used to
#  check for an existing config file and use it to fill in the default
#  answers in the Questions database.  It is only called by the Tk 
#  interface code at this point, although the Curses code could call
#  it.  The Curses code was left pristine so that people choosing to
#  use that interface would not be surprised by new behavior.
#
#  I'm not sure the "special test mode" code works any more.
#
#  I hope I haven't screwed up indentation, but I may have.  Sorry.
#
# My changes are copyrighted (C) 2000 by Paul L. Allen and licensed under
# the GNU General Public License.
#
# Most of the real code here retains Jay's original copyright:
#  
# Copyright (C) 2000 Jay Beale
# Licensed under the GNU General Public License

##########################################
## Bastille Linux Text User Interface   ##
##########################################

#
# TO DO:
#
#  1) Use the newly-release Curses::Widgets 1.1 to get better text windows
#  2) Finish documenting program
#  3) Rewrite &Ask subroutine: either use Curses::Forms or just make cleaner

##########################################################################
# This is the Text User Interface for Bastille Linux Architecture 1,     #
# which is used in Bastille Linux 1.0-1.2.                               #
#                                                                        #
# Bastille Linux's first architecture was primarily streams-based, as it #
# was intended to be a fully interactive Perl script.  Since then, I've  #
# understood that this original interface could be drastically improved, #
# and tried to create a text-based interface which is motivated by RH's  #
# setup utility.                                                         #
#                                                                        #
#                              DATA STRUCTURE                            #
#                                                                        #
# The data structure used to hold the questions is a hash of records,    #
# which are implemented as a secondary hash.  The important part to      #
# understand well is the parent-child relationships between records.     #
# Each question has one or two children.  If it is a Yes/No question and #
# there are questions that should only be asked if the answer was, say,  #
# Yes, then the yes_child will differ from the no_child.  Each question  #
# has a proper_parent item, though.  The easiest way to make sense of    #
# this is by example:                                                    #
#                                                                        #
#  Q1:  Do you wanna answer IPCHAINS questions?                          #
#            yes_child= Q1a   no_child= Q2                               #
#                                                                        #
#     Q1a: ipchains question...  yes_child=no_child=Q1b   parent= Q1     #
#     Q1b: ipchains question 2   yes_child=no_child=Q2    parent= Q1a    #
#                                                                        #
#  Q2:  Wanna talk about sendmail?  proper_parent=Q1                     #
#                                                                        #
#                                                                        #
# OK, so the data structure goes like this...  Each question is indexed  #
# in the outer hash by a short name.  Remember, we're dealing with a     #
# hash of references to hashes, which behaves (thanks Larry) like a      #
# hash of hashes.  If you don't know what a reference is, don't worry    #
# as Perl kinda does something pretty intuitive here (thanks Larry).     #
# Within each question are the following fields:                         #
#                                                                        #
#                              RECORD FIELDS                             #
#                                                                        #
# question        --  question text (ex: wanna do this?)                 #
# short_exp       --  explanation text, at lower detail.                 #
# long_exp        --  explanation text, at high detail. (optional)       #
# default_ans     --  a default answer for the question (optional)       #
# toggle_yn       --  1 if a Yes/No question, 0 if fill-in-the-blank     #
# yes_epilogue    --  epilogue to display after question is asked (opt)  #
# no_epilogue     --  same as above, but displayed if this is y/n        #
#                     question and selected answer was no (optional)     #
# yes_child       --  index of next question, if this is not a Y/N ques. #
#                     or if this is a Y/N ques. and answer=Y             #
# no_child        --  index of next question, if Y/N ques. and answer=N  #
# proper_parent   --  index of "proper" previous question.  This is      #
#                     explained above, but, to recap: this is used so    #
#                     1+-> 1a -> 1b -> 1c -> 2, while 2's parent is 1    # 
#                      +-> 2                                             #
#                                                                        #
#                     where threading is due to 1 being a Y/N question   #
#                                                                        #
# confirm_text    --  this is text added to the end of an answer to      #
#                     maintain compatibility with the 1.0-1.2 ipchains   #
#                     script, which requires that most (but not all) of  #
#                     the user's answers be confirmed with a Y\n         #
#                                                                        #
# answer          --  answer chosen -- this is initially populated by    #
#                     the default_answer field's contents                #
# module          --  associated Bastille modules (automatically set     #
#                         by Load_Questions)                              #
#                                                                        #
#                                                                        #
#                              BASIC OPERATION                           #
#                                                                        #
# The TUI is basically composed of three big subroutines:                #
#                                                                        #
#   Load_Questions -- reads in the question data structure from a flat   #
#                     text file (Questions.txt) and does some sanity     #
#                     checking.                                          #
#                                                                        #
#   Ask            -- goes through all the business of asking a question #
#                     including: calling subs to draw the screen,        #
#                     scroll the explanation, and take input.  It has    #
#                     logic to decide what question should be asked next #
#                     based on answers and returns the index of such     #
#                                                                        #
#   Output_Config_Files -- outputs the configuration file for the        #
#                          Bastille script:   config                     #
#                                                                        #
#                                                                        #
#  For more detail, read the Source, Luke.                               #
#                                            - jjb                       #
#                                                                        #
##########################################################################

sub showUsage {
	print "Usage: InteractiveBastille [ -x | -c ] [--norequires] \n";
	print "           -x : use the Perl/Tk (X11) GUI\n";
	print "           -c : use the Curses (non-X11) GUI\n";
	print " --norequires : ask all questions, even ones that do not\n";
	print "                apply to the current system configuration\n";
	exit 1;
}

# By default, we respect the "requires" tags in Questions.txt and test only is not default
$UseRequiresRules = 'Y';
$TEST_ONLY = 0;

# users on x86 Linux who install the Mandrake perl-Curses
# package will have Curses.pm in a non-standard directory;
# this adds that dir to @INC so we can use Curses
if ( -d "/usr/lib/perl5/site_perl/5.6.0/i386-linux" ) {
	push (@INC,"/usr/lib/perl5/site_perl/5.6.0/i386-linux");
}

# Look for -x or -c interface switches, and shift them off.
# If more than one is present, the last one wins.
# This would be a good place to check for a --keep-config switch.
#
if ( $ENV{DISPLAY} ne '' ) {
	$Interface = "Tk";
} else {
	$Interface = "Curses";
}
while ($ARGV[0] =~ /-.*/) {
    if ($ARGV[0] eq "-x") {
	    $Interface = "Tk";
	} elsif ($ARGV[0] eq "-d") {
	    $nodisclaim="1";
	} elsif ($ARGV[0] eq "-c") {
	    $Interface = "Curses";
	} elsif ($ARGV[0] eq "-T") { # Moved '-T' here so this
                                     # opton no longer makes program exit
	    $TEST_ONLY = 1;
	} elsif ($ARGV[0] eq "--norequires") {
	$UseRequiresRules = 'N';
    } else {
	&showUsage();
    }
    shift @ARGV;
}
if ( $Interface eq 'Tk' && $ENV{DISPLAY} eq '' ) {
	print "ERROR: \$DISPLAY not set, cannot use X interface.\n";
	&showUsage()
}
print "Using $Interface user interface module.\n";
if ( $UseRequiresRules eq 'Y' ) {
	print "Only displaying questions relevant to the current configuration.\n";
} else {
	print "Displaying all questions -- some may not be relevant to the current configuration.\n";
}

for my $interface_module ("Curses", "Tk") {
   if ( $Interface eq $interface_module ) {
      eval "use $interface_module";        
      if ($@) {                    
         die (fill ("", "   "
            ,"FATAL ERROR: The '${interface_module}.pm' interface module could"
            ,"not be found."
            ,"\n\nTROUBLESHOOTING: If you believe that this module is"
            ,"correctly installed, please check the raw error message below;"
            ,"if the installation directory of the module is not listed in"
            ,"\@INC, try reinvoking this script as 'perl -I<module_dir>"
            ,join (" ", $0, @ARGV) . "', where <module_dir> is the"
            ,"directory in which the module resides.  If that does not work,"
            ,"or if you do not have the appropriate module installed, try an"
            ,"alternate interface (perhaps one of './InteractiveBastille -x',"
            ,"'./InteractiveBastille -c', or './AutomatedBastille') or"
            ,"install the missing module.  Hints on which module to install"
            ,"for particular distributions, and download locations for those"
            ,"modules, can be found at"
            ,"<http://www.bastille-linux.org/faq.html>."
            ,"If you contact the Bastille mailing list about this problem,"
            ,"please include the raw error below in its entirety."
            ,"\n\nRAW ERROR:", $@
         ));
      };    
   };
};

use Text::Wrap;
use lib "/usr/lib";
push (@INC,"/usr/lib/perl5/site_perl/");
push (@INC,"/usr/lib/Bastille");
# make sure we don't look in the current directory for the modules!
$i = 0;
foreach $d ( @INC ) {
	if ( $d eq '.' ) {
		# remove "." from @INC for security reasons
		splice(@INC, $i, 1);
	}
	++$i;
}
# Now that we've cleaned up @INC, let's load the API module
#

require Bastille::API;
import Bastille::API;

&showDisclaimer($nodisclaim);  #Require User to Accept Disclaimer


# Select the user interface module.  These modules define somewhat
# different versions of &do_Bastille and the rest of the logic for
# each interface.  
#
# chdir "/usr/lib/Bastille" || die "ERROR: /usr/lib/Bastille unreachable: Bastille not correctly installed?\n";
# chdir is not a healthy way to code... this can create strange dependencies

if ($Interface eq "Tk") {
	require Bastille_Tk;
} elsif ($Interface eq "Curses") {
	require Bastille_Curses;
} else {
	print "Sorry!  Interface $Interface has not been written yet!\n";
	exit;
}

&do_Bastille;

sub Load_Questions {
# sub Load_Questions creates a data structure called %%Questions

###############################################################################
# &Load_Questions does:
#
# 1) Create a question record for the Title screen: no question, no default
#    answer, toggle_yn=0, just a Short Explanation=Title Screen
# 2) Load in each question, one by one, by grabbing the expected records one 
#    by one from a file.  Records, within the file, are described below.  
# 3) Append a "Done now--gonna run the script" screen as Y/N question...  Needs
#    to have Yes-Child to be Bastille_Finish  QuestionName:  End_Screen
#
# Record format within Questions file:
# - A record is terminated by a blank line which is not part of a quoted
#   string.
# - A new record is began by the LABEL: tag, along with the index for the
#   question.
# - Otherwise, the entries within the record can be in any order at all.  
# - Multi-line fields must be quoted in double-quotes..
# - Double quotes are allowed inside a string, but must be escaped, like \".
#
# WEIRD CASES:
#
#  1 If a record has no short_exp explanation, none is shown.  This is bad?
#  2 If a record has no question, no question is asked, but the explanation
#    is still displayed.  If this is the case, the default_answer is still
#    entered into the configuration, if it exists.
#  3 If a question has no answer, it doesn't create any blank lines or such
#    in the output file, as it will be skipped in &Output_Config_Files.  For
#    this reason, &Prompt_Input, which is only called when the record contains
#    a user-answerable question, pads a space to the end of any 0-length input.
#    Not to worry: Output_Config_Files replaces said space with 0-length input
#    NOTE: we couldn't just only print the answer field when a real question
#          existed -- this would improperly handle case 2.
#    
###############################################################################


    # Line loaded in from file and it's non-tag data
    my ($line,$data);
    
    # Line number (within the disk file)
    my $line_number=0;

    # Module to which the current question being loaded in belongs and
    # the order that Load_Questions loads it in
    my $current_module;
    my $current_module_number=0;

    # Question (record) that we're in, listed by index(LABEL) 
    my $current_index;

    # The first and last questions -- used for Title_Screen and End_Screen 
    my $first_question="";
    my $previous_question="";

    # Field we're in
    my $current_field;

    
    # Set up Title Screen
    $Question{"Title_Screen"}{"question"}="";
    $Question{"Title_Screen"}{"short_exp"}=<<END_TITLESCREEN;
                            (Text User Interface)                  

				   v1.3.0


       Please answer all the questions to build a more secure system.
       You can use the TAB key to switch among major screen functions,
       like each question's explanation area, input area and button area.
       Within each of the three major areas, use the arrow keys to scroll
       text or switch buttons.

       Please address bug reports and suggestions to jay\@bastille-linux.org

END_TITLESCREEN

    $Question{"Title_Screen"}{"proper_parent"}="Title_Screen";
    # Pay particularly good attention here! Title_Screen must have the index
    # for the first question...  Load this from the file later!
    $Question{"Title_Screen"}{"yes_child"}="FakeQ1";

    #
    # Load in the questions file, already!
    #

    # OK, so here's how this goes.  The config file looks has a series of
    # records, which have a series of  TAG: value    lines.  A value may span
    # multiple lines if it was begun with a  "  mark, but is usually expected
    # to be a string.  " marks can occur inside records, if escaped:  \"
    # Records end with a blank line and begin with a LABEL: tag.  We get module
    # names from FILE: somename.pm  lines, which should have whitespace around
    # them...

    open QUESTIONS,$GLOBAL_FILE{"Questions"} or die "Can't open ./Questions.txt TUI data file...";
    while ($line=<QUESTIONS>) {

	# Increment line number
	$line_number++;

	# If we're currently in a question record...
	if ($current_index) {

	    # If we're currently in a __multi-line__ record (a quoted string),
	    if ($current_field) {

		# See if it's terminated in a quote (i.e. is end of a string?)
		my $end_of_string=0;

		if ($line =~ /^(.*)\"\s*\n*$/) {
		    # Make sure the terminating quote isn't an escaped quote
		    my $templine=$1;
		    unless ($templine =~ /\\$/) {
			$line=$templine;
			$end_of_string=1;
		    }
		}

		#
		### Text Handling
		#

		# Convert escaped quotes \" to real quotes "
		$line =~ s/\\\"/\"/g;

		# Strip out terminating \n's
		unless ($line =~ /^\s*\n+\s*$/) {
		    if ($line =~ /^(.*)\n$/) {
			$line = $1 . " ";
		    }
		}
		else {
		    $line .= "\n";
		}

		# Add the line to the end of the record and ...
		if ($Question{$current_index}{$current_field} =~ /[^\s\n]$/) {
		    $Question{$current_index}{$current_field} .= " ";
		}

		$Question{$current_index}{$current_field}.=$line;

		# Check if the record is over.
		if ($end_of_string) {
		    $current_field="";
	        }
            }
            else {
                # We're _not_ in a multi-line record
		
		# Did we hit a blank line? Blank lines, not embedded in
		#  " marks, delimit records
		if ($line =~/^\s*$/) {
		    $current_field="";
		    $current_index="";
		}
		else {
		    # Figure out what field to put this data in...
		    
		    if ($line =~ /^SHORT_EXP:(.*)$/) {
			$current_field="short_exp";
		    }
		    elsif ($line =~ /^LONG_EXP:(.*)$/) { 
			$current_field="long_exp";
		    }
		    elsif ($line =~ /^QUESTION:(.*)$/) {
			$current_field="question";
		    }
		    elsif ($line =~ /^DEFAULT_ANSWER:(.*)$/) {
			$current_field="answer";
		    }
		    # What I wouldn't give for a case/switch in Perl...
		    elsif ($line =~ /^YES_EXP:(.*)$/) {
			$current_field="yes_epilogue";
		    }
		    elsif ($line =~ /^NO_EXP:(.*)$/) {
			$current_field="no_epilogue";
		    }
		    elsif ($line =~ /^CONFIRM_TEXT:(.*)$/) {
			$current_field="confirm_text";
		    }
		    elsif ($line =~ /^REQUIRE_IS_SUID:(.*)$/) {
			$current_field="require_is_suid";
		    }
		    elsif ($line =~ /^REQUIRE_FILE_EXISTS:(.*)$/) {
			$current_field="require_file_exists";
		    }
		    elsif ($line =~ /^REQUIRE_DISTRO:(.*)$/) {
			$current_field="require_distro";
		    }
		    elsif ($line =~ /^YN_TOGGLE:(.*)$/) {
			$current_field="toggle_yn";
		    }
		    elsif ($line =~ /^YES_CHILD:(.*)$/) {
			$current_field="yes_child";
		    }
		    elsif ($line =~ /^NO_CHILD:(.*)$/) {
			$current_field="no_child";
		    }
		    elsif ($line =~ /^SKIP_CHILD:(.*)$/) {
			$current_field="skip_child";
		    }
		    elsif ($line =~ /^PROPER_PARENT:(.*)$/) {
			$current_field="proper_parent";
		    }
		    else {
			# UH OH!!! We've found a line (inside a record)
			# that isn't recognized
			print "ERRRRMMMM!!!!!\nThe following line (inside ";
			print "a record is not recognized!\n\n$line\n\n";
			print "Line number: $line_number\n";
			die "Line not recognized!";
		    }

		    # OK, we've know out what field to assign this data to...
		    $data =$1;

		    # Strip off any initiating white space
		    if ($data =~ /^\s+(.*)$/) {
			$data=$1;
		    }
		    
		    # Strip off any terminating white space...
		    if ($data =~ /^(.*)\s+$/) {
			$data=$1;
		    }
		    
		    # If the data isn't quoted, just finish up...
		    unless ( ($data =~ /^\"/ ) or ($data =~ /[^\\]\"$/) ){

			# Convert escaped quote marks
			$data =~ s/\\\"/\"/g;


			# If this is the REQUIRE_DISTRO field, expand any macros
			if ($current_field eq 'require_distro') {
			    
			    # Replace macros with their (by design) hardcoded values,
			    # making sure to respect recursively defined macros.
			    
			    if ($data =~ /\bLINUX\b/) {
				my $supported_distros = 'RH MN';
				$data =~ s/\bLINUX\b/$supported_distros/;
			    }
			    if ($data =~ /\bRH\b/) {
				my $supported_versions = 'RH6.0 RH6.1 RH6.2 RH7.0 RH7.1 RH7.2';
				$data =~ s/\bRH\b/$supported_versions/;
			    }
			    if ($data =~ /\bMN\b/) {
				my $supported_versions = 'MN6.0 MN6.1 MN6.2 MN7.0 MN7.1 MN7.2 MN8.0 MN8.1 MN8.2';
				$data =~ s/\bMN\b/$supported_versions/;
			    }
			    if ($data =~ /\bDB\b/) {
				my $supported_versions = 'DB2.2';
				$data =~ s/\bDB\b/$supported_versions/;
			    } 
			    if ($data =~ /\bSE\b/) {
                                my $supported_versions = 'SE7.2';
                                $data =~ s/\bSE\b/$supported_versions/;
                            }
                            if ($data =~ /\TB\b/) {
                                my $supported_versions = 'TB7.0';
                                $data =~ s/\bTB\b/$supported_versions/;
                            }
			    if ($data =~ /\bHP-UX\b/) {
				my $supported_versions = 'HP-UX11.00 HP-UX11.11';
				$data =~ s/\bHP-UX\b/$supported_versions/;
			    }
			}


			$Question{$current_index}{$current_field}=$data;

			$current_field="";
		    }
		    else {
			# Make sure this looks like a real quoted string
			if ($data !~ /^\s*\"/) {
			    print "ERROR: Weird quoted line\n\n$line\n\n";
			    print "Line number $line_number\n";
			    die "quoted line without quote at beginning of line";
			}

			# Strip off initiating quote mark
		        if ($data =~ /^\s*\"(.*)$/) {
			    $data=$1;
			}

			# If this thing has a terminating quote mark, it is a
			# single-line quoted record, probably used to preserve
			# leading or trailling whitespace.
			if ($data =~ /[^\\]\"$/) {
			    
			    if ($data =~ /^(.*)([^\\])\"$/) {
				$data=$1 . $2;
				
				# Convert escaped quote marks
				$data =~ s/\\\"/\"/g;

				$Question{$current_index}{$current_field}=$data;
				$current_field="";
			    }
			}
			# Otherwise, it is the beginning of a multi-line record
			else {

			    # Strip off end \n's
			    unless ($data =~ /^\s*\n+\s*$/) {
				if ($data =~ /^(.*)\n$/) {
				    $data=$1 . " ";
				}
			    }
			    
			    # Convert escaped quote marks
			    $data =~ s/\\\"/\"/g;

			    # Now, actually copy the data in
			    $Question{$current_index}{$current_field}=$data;
			}
		    }		 
		}
	    }
	}
	# OK, so we're not in a record (Question) at all...
	else {

	    # Are we starting a new one, on another blank line, or getting a
	    # module name?
	    if ($line =~ /^LABEL:\s*(.*)$/) {

		# We have found a new record...
		$current_index=$1;

		# Prune whitespace from the name
		if ($current_index=~/^(.*)\s+$/) {
		    $current_index =$1;
		}

		$Question{$current_index}{"module"}=$current_module;
		$current_field="";  # This is not a multi-line record

                # Record the name of the record so sanity checks can be done
		# later
		$recordnames[@recordnames]=$current_index;
		
		# If this is the first record (question), make the necessary
		# link from Title_Screen record
		unless ( $first_question ) {
		    $first_question=$current_index;
		}
		
		# Save the value of the current index so the End_Screen can
		# find the right parent...
		$previous_question=$current_index;

	    }
	    elsif ($line =~ /^FILE:\s*(.*)$/) {
		# Started a new module name...
		$current_module_number++;
		$current_module=$1 . " Module $current_module_number";
	    }
	    elsif ($line =~ /^\s*$/) {
		# A blank line
		# do nothing
	    }
	    else {
		# Something unexpected!
		print "Something weird discovered between question records:\n";
		print "$line\n\n";
		print "Line number $line\n";
		die "Problem with question file -- something strange found between question records!";
	    }
	}
    }
    close QUESTIONS;


    #
    # Set up Title_Screen and last question: "Can we run now?" screen 
    #

    $Question{"Title_Screen"}{"yes_child"}=$first_question;
    $Question{$first_question}{"proper_parent"}="Title_Screen";
    $Question{"End_Screen"}{"proper_parent"}=$previous_question;
    $Question{$previous_question}{"yes_child"}="End_Screen";
    $Question{$previous_question}{"no_child"}="End_Screen";

    $Question{"End_Screen"}{"short_exp"}="We will now implement the choices you have made here.\n\nAnswer NO if you want to go back and make changes!\n";
    $Question{"End_Screen"}{"question"}="Do you want to implement the choices now or continue making choices?";
    $Question{"End_Screen"}{"toggle_yn"}=1;
    $Question{"End_Screen"}{"yes_child"}="RUN_SCRIPT";
    $Question{"End_Screen"}{"no_child"}="End_Screen";
    $Question{"End_Screen"}{"no_epilogue"}= <<END_BACK_NEXT;
Please use Back/Next buttons to move among the questions you wish to change.


      Choose YES on this question later to implement your choices.
END_BACK_NEXT

    ##############################################
    # Walk through $Question hash, eliminating   #
    # questions that don't apply to this system. #
    #                                            #
    # Use the new requires- fields to figure out #
    # which questions to prune.  Prune by simply #
    # moving the parent/child pointers to skip   #
    # around the question.                       #
    #                        - JJB 3/2001        #
    ##############################################

    my $key;
    foreach $key (@recordnames) {

		#print "Key: $key\n";
	my $require_file_exists=$Question{$key}{"require_file_exists"};
	my $require_distro=$Question{$key}{"require_distro"};
	my $require_is_suid=$Question{$key}{"require_is_suid"};

	my @require_is_suid;
	my @require_distro;
	my @require_file_exists;

	# There should be a smarter way to do this....

	# Pull each hash entry (separated by spaces) off the $string,
	# look it up, then add the hash entry into @array.

	#print "Parsing suid requirement tag: $require_is_suid\n";
	@require_is_suid_raw = split " ",$require_is_suid;
	foreach $file ( @require_is_suid_raw ) {
	    $file =~ s/\s*//g;
	    #print "Checking $file with pathname $GLOBAL_BIN{$file}\n";
	    push @require_is_suid,$GLOBAL_BIN{$file};
    	}
	
	#print "Parsing requires file tag $require_file_exists\n";	
	# Pull each hash entry (separated by spaces) off the $string,
	# look it up, then add the hash entry into @array.
	@require_file_exists_raw = split " ",$require_file_exists;
	foreach $file (@require_file_exists_raw) {
	    $file =~ s/\s*//;
	    push @require_file_exists,$GLOBAL_FILE{$file};
	}
 	 
	#print "Parsing requires_distro tag: $require_distro\n";	
	# Pull each distro from the $string and add it to the array
	(@require_distro) = split " ",$require_distro;
	#print "Got list ";
	#print @require_distro;
	#print "\n";
	
	# Test these REQUIRE tags.  If the question does not fit, then
        # juggle the pointers.
	
	my $skip_this_question=0;
	
    # Test all requires if we're following requires rules
    #
    # Note: seperate types of requires are and'ed while all of the
    #       same type of requires are or'ed.
    #
    # Example:
    # REQUIRE_IS_SUID: foo bar
    # REQUIRE_FILE_EXISTS: alpha beta gamma
    # REQUIRE_DISTRO: RH6.0 HP-UX11.00
    #
    # should return true iff
    # (either foo or bar is SUID) and
    # (any of alpha, beta, or gamma exist) and
    # (we are on a RH6.0 or HP-UX11.00 machine)
    #
	if ( $UseRequiresRules eq 'Y') {
	    #print "About to check out suid programs\n";
	    if ( @require_is_suid ) {
		my $file_is_suid=0;
		foreach $file ( @require_is_suid ) {
		    #print "Testing for suid status of -- $file --\n";
		    if ( -u $file) {
			$file_is_suid=1;
		    }
		}
		
		unless ($file_is_suid) {
		    $skip_this_question++;
		    #print "no files were SUID -- setting for skip\n";
		}
	    }
	    #print "Passing suid test -- $skip_this_question\n";
	    
	    if ( @require_file_exists ) {
		my $file_exists=0;
		foreach $file ( @require_file_exists ) {
		    #print "Testing for file $file\n";
		    if ( -e $file) {
			$file_exists=1;
		    }
		}
		
		unless ($file_exists) {
		    $skip_this_question++;
		    #print "files did not exist -- setting for skip\n";
		}
	    }
	    #print "Passing file test -- $skip_this_question\n";
	    
	    if ( @require_distro ) {
		my $tmp = @require_distro;
		#print "There are $tmp distros in the list\n";
		my $distro_is_appropriate=0;
		#print "Remember, distro is $GLOBAL_DISTRO\n";
		foreach $distro ( @require_distro ) {
		    #print "Testing for distro $distro\n";
		    if ($distro eq $GLOBAL_DISTRO ) {
			$distro_is_appropriate=1;
		    }
		}
		
		unless ($distro_is_appropriate) {
		    $skip_this_question++;
		    #print "Distro was not appropriate -- setting for skip\n";
		}
	    }
	    
	    #print "Passing distro test -- $skip_this_question\n";
	}  # end loop of testing requirements if asked to follow "requires" rules
	
	# OK, if we didn't meet all the requirements, skip this question.
	# 
	# This is rudimentary pointer mangling.  There are serious speed-ups
	# that we can make by thinking more about tree transversals -- this 
	# is the "simple" implementation intended to introduce the 
	# functionality.  Let's speed it up later, for 1.2.x, x>0.
	#
	# - JJB 3/2001

	#print "skip_this_question=$skip_this_question\n";
	if ($skip_this_question) {

	    my $parent=$Question{$key}{"proper_parent"};
	    my $child;
	    
	    # Choose the next question to go to carefully
	    if ($Question{$key}{"yes_child"} eq $Question{$key}{"no_child"}) {
		$child = $Question{$key}{"yes_child"};
	    }
	    else {
		$child = $Question{$key}{"skip_child"};
	    }
	    #Now do the pruning.
	    if ($child) {

		my $loop_over_key;
		#print "Pruning $key\n";
		foreach $loop_over_key (keys(%Question)) {
		    
		    # Any questions which have the phantom question as a child
		    # should now point to the phantom's child instead.
		    if ($Question{$loop_over_key}{"yes_child"} eq $key) {
			$Question{$loop_over_key}{"yes_child"}=$child;
		    }
		    if ($Question{$loop_over_key}{"no_child"} eq $key) {
			$Question{$loop_over_key}{"no_child"}=$child;
		    }
		    # This gets tricky...think about this one deeply before
		    # emailling me on this.  - JJB
		    if ($Question{$loop_over_key}{"proper_parent"} eq $key) {
			$Question{$loop_over_key}{"proper_parent"}=$parent;
		    }
		}
	    }
	    else {
			print "Question $key couldn't be skipped -- couldn't figure out which question to skip to!\n";
	    }
	}

    }
    ##############################################
    #   Run sanity checks on questions database  #
    ##############################################

    my $key;
    foreach $key (@recordnames) {

	my ($parent,$yes_child,$no_child);
	
	$parent=$Question{$key}{"proper_parent"};
	$yes_child=$Question{$key}{"yes_child"};
	if ($Question{$key}{"toggle_yn"}) {
	    $no_child=$Question{$key}{"no_child"};
	}

	if ($TEST_ONLY) {
	    print "\nChecking key $key\n";
	    print "Yes-child $yes_child\n";	    
	    print "No-child no_child\n";
	    print "Proper_parent $parent\n";
	
	    print "-"x10 . "Spewing record $key\n";
	    print $Question{$key}{"short_exp"};
	    print "\nlong_exp:\n";
	    print $Question{$key}{"long_exp"};
	    print "\nquestion:\n";
	    print $Question{$key}{"question"};
	    print "\nanswer\n";
	    print $Question{$key}{"default_answer"};
	    print "\nyes_child\n";
	    print $Question{$key}{"yes_child"};
	    print "\nno_child\n";
	    print $Question{$key}{"no_child"};
	    print "\nparent\n";
	    print $Question{$key}{"proper_parent"};
	    
	    print "\n\n";
	}

	die "Question database corrupt! $key: no parent!" unless $parent;
	die "Question database corrupt -- $key \'s parent doesn't exist" unless (defined($Question{$parent}));
	die "Question database corrupt -- $key \'s yes_child doesn't exist" unless (defined($Question{$yes_child}));

	die "Question database corrupt! $key: no yes-child" unless $yes_child;
	if ($Question{$key}{"toggle_yn"}) {
	    die "Question database corrupt! $key: no no_child on y/n question" unless ($no_child);
	    die "Question database corrupt -- $key \'s no_child doesn't exist" unless (defined ($Question{$no_child}));
	    die "Question database corrupt -- y/n question $key has no Question!" unless ( $Question{$key}{"question"} );

	}


    }

    if ($TEST_ONLY) {
	exit;
    }      

    # Return number of modules loaded in
    $current_module_number;

}

sub Load_Questions_Stub {
# sub Load_Questions creates a data structure called %%Questions
    
    # Set up Title Screen
    $Question{"Title_Screen"}{"question"}="";
    $Question{"Title_Screen"}{"short_exp"}=<<END_TITLESCREEN;
                                Bastille Linux                          

	       	      (Text User Interface ver 1.00pre1)                  

			       SPECIAL TEST MODE



			            (jjb)


			         ( PRESS TAB )
END_TITLESCREEN

    $Question{"Title_Screen"}{"yes_child"}="FakeQ1";
    $Question{"Title_Screen"}{"proper_parent"}="Title_Screen";

    # Create a fake question 1 for testing purposes
    $Question{"FakeQ1"}{"short_exp"}="This is the\nfake question\n";
    $Question{"FakeQ1"}{"long_exp"}="This\nis\nthe\nlong version\nof the\nfake question.";
    $Question{"FakeQ1"}{"question"}="Do you want to do this?";
    $Question{"FakeQ1"}{"yes_child"}="FakeQ2";
    $Question{"FakeQ1"}{"proper_parent"}="Title_Screen";
    $Question{"FakeQ1"}{"yes_epilogue"}="OK, we did it";
    $Question{"FakeQ1"}{"toggle_confirm"}="1";

    $Question{"FakeQ2"}{"short_exp"}= <<END_DETAIL_SETTING;
We will be setting the default level of detail of the explanations to Longer Explanations.  You can toggle this, as many times as you like, at each question by TAB-bing over to the DETAIL button and hitting Enter/Space.

Please select NEXT to go to the next question.
END_DETAIL_SETTING

    $Question{"FakeQ2"}{"answer"}="Y";
    $Question{"FakeQ2"}{"proper_parent"}="FakeQ1";
    $Question{"FakeQ2"}{"yes_child"}="End_Screen";

    # Set up last question: "Can we run now?" screen -- careful about Parent!!!
    $Question{"End_Screen"}{"proper_parent"}="FakeQ2";
    $Question{"End_Screen"}{"short_exp"}="We will now implement the choices you have made here.\n\nAnswer NO if you want to go back and make changes!\n";
    $Question{"End_Screen"}{"question"}="Are you finished answering the questions, i.e. may we make the changes?";
    $Question{"End_Screen"}{"toggle_yn"}=1;
    $Question{"End_Screen"}{"yes_child"}="RUN_SCRIPT";
    $Question{"End_Screen"}{"no_child"}="End_Screen";
    $Question{"End_Screen"}{"no_epilogue"}="Please use Back/Next buttons to move among the questions you wish to\nchange.\n\nChoose YES on this question later to implement your choices.\n";

    
    1;
}


sub Output_Config_Files {

##############################################################################
# %Output_Answers will:
#
# 1) write out a file, which can be read by our parser, containing the full
#    contents of the questions data structure
#
# More information coming here, from design doc...
#
# WEIRD CASES:
#
#  1 If a record has no short_exp explanation, none is shown.  This is bad?
#  2 If a record has no question, no question is asked, but the explanation
#    is still displayed.  If this is the case, the default_answer is still
#    entered into the configuration, if it exists.
#  3 If a question has no answer, it doesn't create any blank lines or such
#    in the output file, as it will be skipped in &Output_Config_Files.  For
#    this reason, &Prompt_Input, which is only called when the record contains
#    a user-answerable question, pads a space to the end of any 0-length input.
#    Not to worry: Output_Config_Files replaces said space with 0-length input
#    NOTE: we couldn't just only print the answer field when a real question
#          existed -- this would improperly handle case 2.
#    
##############################################################################

#    open RAW_CONFIG,"> tui-generated-raw-config";
	mkdir $GLOBAL_BDIR{"config"},0700;
	open FORMATTED_CONFIG, "> $GLOBAL_BFILE{'config'}" or die "Couldn't write config file: " . $GLOBAL_BFILE{'config'};
#    open FORMATTED_CONFIG,"> /etc/Bastille/config" or die "Couldn't write config file /etc/Bastille/config!"; # removed hard coded path

    my $index="Title_Screen";
    my $module="";

    while ($index ne "End_Screen") {

	# We used to generate the module headers for AppConfig
	#if ($Question{$index}{"module"} ne $module ) {
	#    print FORMATTED_CONFIG "[ $module ]\n";
	#}

	if ($Question{$index}{"answer"}) {

	    # If the answer is just a space (the way the &Prompt_Input sub
	    # designates a blank line, strip it.
	    
	    if ($Question{$index}{"answer"} =~ /^\s$/) {
		$Question{$index}{"answer"} = "";
	    }

	    # Print the raw input for the Bastille 1.0 script series 
#	    print RAW_CONFIG "### Question index $index\n";
	    if ($Question{$index}{"question"}) {
#		print RAW_CONFIG "### Question text  ";
#		print RAW_CONFIG $Question{$index}{"question"} . "\n";
	    }

	    # The "confirm_text" data element fixes a problem caused by the
	    # different way that IPChains handles input.  In the IPCHAINS 
	    # module, there are two critical items:
	    # 
            #  1) if the user enters an empty string (by hitting enter),
	    #     IPCHAINS replaces this with the default answer.  A true
	    #     "empty" result reqires that the user enter 
	    #     something (ie, a space)
	    #  2) Most (not _all_) of the questions require a Y\n confirmation
	    #
	    # By including confirmation text, we can kill the first difference
	    # by having the confirm text include a " ".  Should the question
	    # also need a confirming Y, this can be included by making the
	    # confirmation text " \nY".
	    # Note: to make this work, we have to fix \n's...
	    
#	    print RAW_CONFIG $Question{$index}{"answer"};
	    $Question{$index}{"confirm_text"} =~ s/\\n/\n/g;
#	    print RAW_CONFIG $Question{$index}{"confirm_text"};
#	    print RAW_CONFIG "\n";

	    # Print formatted file too...
	    my $module = $Question{$index}{"module"};
	    if ($module =~ /^([^.]+).pm/) {
		$module =$1;
	    }
	    print FORMATTED_CONFIG "# Q: " . $Question{$index}{"question"} . "\n";
	    print FORMATTED_CONFIG "$module.";
	    print FORMATTED_CONFIG $index . "=\"";
	    print FORMATTED_CONFIG $Question{$index}{"answer"} . "\"\n";
	    
	}
	if ($Question{$index}{"toggle_yn"} == 0) {
	    $index=$Question{$index}{"yes_child"};
	}
	else {
	    if ($Question{$index}{"answer"} =~ /^\s*Y/i) {
		$index=$Question{$index}{"yes_child"};
	    }
	    elsif ($Question{$index}{"answer"} =~ /^\s*N/i) {
		$index=$Question{$index}{"no_child"};
	    }
	    else {
#		print RAW_CONFIG "Major error on question $index!\n";
		print "Major error on y/n question $index -- answer not y/n !\n";
	    }
	}
    }
    close FORMATTED_CONFIG;
#    close RAW_CONFIG;

}



sub Run_Bastille_with_Config {
    
    system "/usr/sbin/BastilleBackEnd";
}

# A hacked copy of ReadConfig from Bastille/API.pm to populate the
# questions database with  answers from an existing config file.
#
# If the structure of the Questions.txt file changes in a way that
# requires a change in API.pm, this function will probably need
# changing as well.  It might have been better to put this change
# in API.pm, but I wanted to keep the number of changed files to
# a minimum.  (PLA)
#
sub Populate_Answers {

    if (open CONFIG, $GLOBAL_BFILE{"config"}) {
	print "Existing config file found.  Populating answers...\n";
	while (my $line = <CONFIG>) {
    
#	    Skip commented lines...
#
	    unless ($line =~ /^\s*#/) {
		if ($line =~ /^\s*(\w+).(\w+)\s*=\s*\"(.*)\"/ ) {
		    if ($3 eq "") {

#			Null answers need a space in order to show up 
#			in output file.
#
			$Question{$2}{'answer'} = " ";
		    } else {
			$Question{$2}{'answer'} = $3;  
		    }
		}
	    }
	}
	close CONFIG;
    } else {
	print "Could not open config: ", $GLOBAL_BFILE{"config"},", defaults used.\n";
    }
}

