#!/var/opt/STORtools/bin/perl

require  "subroutines.pm";
&st_globals();

$output = `/usr/bin/ksh -c '/usr/sbin/luxadm -e port 2>&1'`;
if ($output =~ /subcommand not specified/) {
   $oslevel = `/usr/bin/uname -r`;
   chomp $oslevel;
   if ($oslevel eq "5.5.1") {
       print "StorTools is not supported on $oslevel\n";
       exit 1;
   }
   $patch = `grep luxadm config-matrix | grep $oslevel`;
   my ($os, $patch) = split /:/, $patch;
   $patch =~ s/\s+//g;
   print "You need to install a newer version of luxadm.\n";
   print "Refer to patch $patch or newer on http://sunsolve.sun.com\n";
   exit 1;
}

$PROGNAME   = "stormenu";
$LOG_SUM    = "$LOGDIR/diags/test_summary";

use Date::Parse;
use Date::Format;

#$DEBUG = "TRUE";

&st_header( "version" );

print <<END;

   NOTICE: Use of this software and associated packages is authorized  
   ONLY by personnel trained in its use and trained on the Products 
   for which it was intended to be used on.
   
   The execution of this toolkit assumes the user accepts the licensing
   terms and agreements as contained in the file NOTICE.txt.

END

if ( &checkLogDevice() < 10000000 ) { 

    printf("Warning: ${PRODUCT} has less than 10 megabytes on the [/var] filesystem.\n");
    printf("This may not be enough for this session of ${PRODUCT}.\n");   

    printf("Continue? [<y>, n]: ");
    $cmd = &get_response("y");
    exit 0 if ( $cmd =~ /^n/i );

}

###############################################################
# Menu program for Diagnostic Toolkit
# 
# Copyright (c) 1998  Sun Microsystems Computer Corporation, Inc.
###############################################################

$VERITAS = '';
($VERSION) = grep { s/VERSION:\s+(\S.*)\s$/$1/ } `/usr/bin/pkginfo -l ${PKGNAME}`;

&check_root_access( $PROGNAME );

$GOLD_PATH  = "${LOGDIR}";

if ( ! $CDROM ) {
    &check_entry_reqs();
}

&proc_cli;

if ($SHORT_INIT eq "FALSE") {
    $IC_ARG = "";
} else {
    $SHORT_TEST = "TRUE";
}

&initcheck;

print "Press <return> to continue ... ";
&get_response;

$SIG{INT} = 'int';
$cmd = "";


while ($cmd ne "q") {
    &print_menu;
    $cmd = &get_response; 
    if ( $cmd =~ /^q/i ) {
        $cont = 1;
        while($cont) {
            if (procs_a_runnin($LOGDIR)) {
                printf("\nProcesses are running in background. You may quit to\n"); 
                printf("leave processes running or selectively terminate.\n"); 
                printf("[<quit>, s=show, a=kill all, c=kill by controller]: ");
                $ans = &get_response; 
                if ($ans eq "" || $ans =~ /^q/i ) {
                    printf("Exiting stormenu...\n");
                    exit 0;
                }
                if($ans =~ /^c/i ) { 
                    kill_pid_files($LOGDIR, "c");
                }
                if($ans =~ /^a/i) {
                    kill_pid_files($LOGDIR, "k");
                    printf("Exiting stormenu...\n");
                    exit 0;
                }
                if($ans =~ /^s/i) {
                    show_pid_files($LOGDIR);
                }
            } else {
                $cont = 0;
            }
        }
        printf("Exiting stormenu...\n");
        exit 0;
    }
    if ( $cmd eq 1 ) {
        system_clear();
        my $default_args = "-all -log -warn";
        my $current_args = "-all -log -warn";
        my $choice;

        while ($choice !~ /^q/i) {
            &st_header();
            print "Menu: Revision Check\n";
            print "--------------------\n";
            &st_matrix_msg();
            print "This probe can take 30 seconds per array to complete.\n\n";
            print "[r] Run with ";
            if ($default_args eq $current_args) {
                print "Default Options\n";
            } else {
                print "User Defined Options\n";
            }
            print "[s] Select Options\n";
            print "[q] Quit\n";
            print "\nEnter Choice [<r>, s, q]: ";
            $choice = &get_response( "r" );
            if ($choice =~ /^s/i) {
                $current_args = &storstat_options($default_args, $current_args);
            } elsif ($choice =~ /^r/i) {
                print "Please wait for system probe... \n";
                print "\n",`/usr/bin/date` if ($TIMEIT);
                $result = `${BINDIR}/storstat $current_args`;
                print $result;
                print "\n",`/usr/bin/date` if ($TIMEIT);
                print "\nPress <return> to continue ...";
                &get_response;
                # $choice = "q";
            #} elsif ($choice =~ /^d/i) {
                # secret option to display storstat arguments #
                #print "\nDefault Options: $default_args\n";
                #print "Current Options: $current_args\n\n";
            } elsif ($choice =~ /^q/i) {
                next;
            } else {
                print "\n$choice is an invalid choice!\n";
            }
        }
        next;
    } elsif ( $cmd eq 2 ) {
        &create_snapshot();
    } elsif ( $cmd eq 3 ) {
        &disp_conf_menu;
    } elsif ( $cmd eq 4 ) {
        AGAIN:
        print "\nThis command uses the Configuration Snapshot File as the baseline\n";
        print "storage configuration state.  It then examines the live system to\n";
        print "check the current storage configuration and looks for change.\n\n";
        $golden_snapshot = &get_golden_snapshot;
        if ($golden_snapshot) {
            print "This command can take 30 seconds per array to complete.\n";
            print "Would you like to continue? [<y>, n]: ";
            $yorn = &get_response("y");
            if ($yorn !~ /^y/i) {
                next;
            }
            print "\nCheck Current Status\n";
            print "Please wait for system probe...\n";
            print "\n",`/usr/bin/date` if ($TIMEIT);
            $result = `${BINDIR}/storconfig -cmp -log `;
            print $result;
            print "\n",`/usr/bin/date` if ($TIMEIT);
        } else {
            print "Configuration Snapshot File does not exist.\n";
            print "Would you like to create the Configuration Snapshot File now[<y> ,n]: "; 
            $yorn = get_response();
            if ($yorn =~ /^n/i) {
                next;
            }

            $res = &create_snapshot(); 
            if($res == 0) {
                printf("Continuing comparison with live system....\n");
                goto AGAIN;
            }
        }

        print "\nPress <return> for previous menu ...";
        &get_response;
    } elsif ( $cmd eq 5 ) {
        &proc_monitor_menu;
    } elsif ( $cmd eq 6 ) {
        &proc_diag_main_menu;
    } elsif ( ( $cmd eq 7 ) && ( !defined $LITE ) ) {
        system "${BINDIR}/ivmenu";
    } elsif ( $cmd =~ /^[h|?]/i) {
        system_clear();
	&st_header();

                system "/usr/bin/more $PKGDIR/docs/main.help";

        print "\nPress <return> to continue ...";
        &get_response;
    } else {
        print "\n$cmd is an invalid option!\n";
    }
}

###############################################################
#           SUBROUTINES
#           SUBROUTINES
#           SUBROUTINES
###############################################################

###############################################################
# get the date from the snapshot
###############################################################
sub get_snapshot_date {
    $gold_snap = &get_golden_snapshot;
    if (($gold_snap ne "") & (-e "${GOLD_PATH}/${gold_snap}")) {
        unless (open(GOLD, "<${GOLD_PATH}/${gold_snap}")) {
            $GS_DATE = "Unable to open Gold Snapshot";
            return;
        }
        foreach $line (<GOLD>) {
            if ($line =~ /\w{3,3}\s+\w{3,3}\s+\d+\s+\d{1,2}:\d{2,2}:\d{2,2}\s+\w+\s+\d{4,4}/) {
                $GS_DATE = $line;
                last;
            } else {
                $GS_DATE = "No date";
            }
        }
        close GOLD;
    } else {
        $GS_DATE = "No Gold Snapshot";
    }
}

###############################################################
# print_menu
###############################################################
sub print_menu {
    &get_snapshot_date;
    &system_clear();
    &st_header();
    print "Menu: Main\n";
    print "----------\n\n";
    print " [1] Check Revisions\n";
    print " [2] Create Configuration Snapshot File\n";
    print " [3] Display Configuration\n";
    print " [4] Check Current Status\n";
    print " [5] Storage Monitor\n";
    print " [6] Run Diagnostics\n";
    if ( !defined $LITE ) {
        print " [7] Installation Verification\n";
    }
    print "\n";
    print " [?] Display Help\n";
    print " [q] Quit\n";
    print " \n";
    my $cur_date = `/usr/bin/date`;
    my $goldfile = &get_golden_snapshot;
    print "  Current Date:\t\t$cur_date";
    if ($goldfile eq "") {
       print "  Gold Snapshot file is not present!\n";
    } else {
       print "  Gold Snapshot date:\t$GS_DATE";
       print "  Gold Snapshot path:\t${GOLD_PATH}/${goldfile}\n";
    }
    print "\n";
    print "Select an operation to perform: ";
}






sub fetch_date {

    my @a;
    my @b;

    my @valid_months = (
	"January",
	"February",
	"March",
	"April",
	"May",
	"June",
	"July",
	"August",
	"September",
	"October",
	"November",
	"December"
    );

    my @valid_no_days = (
	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );

    # $datevar is a reference variable, $pstring and $default are strings

    my ($datevar, $pstring, $default) = @_;
    
    while (!defined($$datevar)) {

        print $pstring;

        my $tmpv = get_response($default);

        if ($tmpv =~ /^q/i) {
            $$datevar = $tmpv;
            return;
        }



        if ($tmpv eq $default) {

            $$datevar = $default;

        } else {


	    if (! ($tmpv =~ /\//) )  {
		$timeOnly = 1;
	    } else {
		$timeOnly = 0;
	    }
			
	    
	    $timeFracs = "";

 	    my @t = split(/:/ , $tmpv);

	    if(($#t > 0) && $timeOnly) {
		$timestring = "";
		$timeFracs = $tmpv;
	    } else {
		for($i = 1; $i <= $#t; $i++) {
			$timeFracs .= ":" . "$t[$i]";
		}
		$timestring = $t[0];
	    }


            if($timestring =~ /\//) {

                @a = split(/\//, $timestring); 


                if (  defined($a[2]) ) {

			$year = $a[2];
			if ( ! ($year =~ /\d{4}/) ) {
				printf("Invalid year:  must be 4 digits. Please try again...\n");
				next;
			}

                } else {

		        $year =  time2str("%Y", time);


		        $timestring .= "\/$year";

		}

		$leap_year = $year % 4;

	        if ( $leap_year == 0 ) {
			$valid_no_days[ 1 ] = 29;
                }

                if( $a[0] <= 0 || $a[0]  > 12 ) {
                    printf("Invalid month$a[0] <1-12>. Please try again\n");
                    next;
                }

                if( $a[1] <= 0 || $a[1]  > $valid_no_days[ $a[0] - 1 ] ) {
                    printf("Invalid day($a[1]) in @valid_months[ $a[0] - 1 ]. Please try again\n");
                    next;
                }
		$tmpv = $timestring . $timeFracs;

            } else {  # just gave hours, minutes

		$timestring =  time2str("%m/%d/%Y:", time);
		$timestring .= $timeFracs;
		$tmpv = $timestring;
	    }
    
            my $t = str2time $tmpv;

	
    
            if (!defined $t ) {
                print "Invalid date: $tmpv  Please try again.\n";
            } else {
                $$datevar = $tmpv;
            }
        }
    }
}








###############################################################
# Process the message summary menu items
###############################################################
sub proc_mess_sum {

    my $oneDayOfSeconds = (24 * 60 * 60);

    while (1) {
        #' for emacs
        my @ford =
      (
       "Menu: Messages Summary\n",
       "----------------------\n",
       "\n",
       "This menu function will scan the specified system messages file and\n",
       "produce a summary of all Storage related events. The program will\n",
       "prompt for the messages file or directory, start and end dates. The\n",
       "system's snapshot or storage configuration file will be used if\n",
       "available for better device translation.\n",
       "\n",
       "Start and End dates must be given in the following format:\n",
       "\n",
       "month/day/year:hour:minute\n",
       "\n",
       "Example:\n",
       "11/12:9:00  - November 12, 9:00am\n",
       "11/12       - November 12, midnight\n",
       "18:00       - 6:00pm of the current day\n",
       "\n",
       " [1] Summarize a single messages file\n",
       " [2] Summarize multiple messages files in a directory\n"
      );
        my $mdir;
        my $ford;
        $ford = &do_menu(\@ford);
        last if ($ford =~ /^q/i);
        if ($ford == 1) {
            $ford = '-f';
            print "Message file: [</var/adm/messages>, /dir/file, q] ";
            $mdir = get_response('/var/adm/messages');
            next if ($mdir =~ /^q/i);
            if (($T300_PRESENT) and ($mdir ne "/var/adm/messages.t300")) {
                print "Summarize file /var/adm/messages.t300 also? [<y>, n] ";
                my $also = &get_response('y');
                $mdir .= ",/var/adm/messages.t300" if ($also =~ /^y/i);
            }
        } elsif ($ford == 2) {
            $ford = '-dir';
            print "Messages directory: [</var/adm>, q]: ";
            $mdir = get_response('/var/adm');
            next if ($mdir =~ /^q/i);
        } else {
            print "\n";
            print "$ford is an invalid option!\n";
            next;
        }
        my $sdate = undef;

        my $now = `/usr/bin/date '+%m/%d/%Y:%T'`;
        chomp $now;

        my $cur_month = `/usr/bin/date '+%m'`;
        my $cur_day = `/usr/bin/date '+%d'`;
        my $cur_year = `/usr/bin/date '+%Y'`;
	my $time = time - $oneDayOfSeconds;
	my $default_date = time2str("%m/%d/%Y:%T", $time);
#        my $default_date = pack "a2aa2aa4", $cur_month, "/", $cur_day, "/", $cur_year;

        &fetch_date(\$sdate, "Start date [ <${default_date}>, mm/dd/yyyy, mm/dd/yyyy:hh:mm, q] ", $default_date);
        next if ($sdate =~ /^q/i);
        $sdate = $default_date if ($sdate eq "");
        my $edate = undef;
        &fetch_date(\$edate, "End date [ <$now> , mm/dd/yyyy, mm/dd/yyyy:hh:mm, q] ", time2str("%m/%d/%Y:%T", time));
        next if ($edate =~ /^q/i);
        $edate = time2str("%D:%T", time) if ($edate eq "");
        printf("Start Date: $sdate End Date: $edate\n");
        print "Capture summary to file [<n>, y] ";
        my $y_or_n = &get_response("n");
        if ($y_or_n =~ /^y/i) {
            print "Enter capture filename: ";
            $capture_filename = &get_response;
        }
        print "\n";
        my $temp_mess = "/tmp/mess_sum.$$";
        unlink $temp_mess;
        if ($capture_filename ne "") {
            $rs = sprintf "$BINDIR/mess_sum %s %s -F %s -s %s -e %s >$temp_mess", "$ford", "$mdir", "$capture_filename", "$sdate", "$edate";
        } else {
            $rs = sprintf "$BINDIR/mess_sum %s %s -s %s -e %s >$temp_mess", "$ford", "$mdir", "$sdate", "$edate";
        }
        system $rs;
        system '/usr/bin/more', "$temp_mess";
        `rm $temp_mess`;
        printf("\nPress <return> to continue...");
        &get_response;
    }
}

###############################################################
# Monitor Menu Controls
###############################################################
sub proc_monitor_menu {
    my @monitor_menu = 
      (
       "Menu: Storage Monitor \n",
       "---------------------\n\n",
       " [1] Storage Messages Summary\n",
       " [2] Storage Status Check Setup\n",
      );
D_MONITOR_MENU:
    my $cmd = do_menu(\@monitor_menu);
    return if ($cmd =~ /^q/i);
    if ($cmd eq 1) {
        &proc_mess_sum;
    } elsif ($cmd eq 2) {
        system "${BINDIR}/storcron";
    } else {
        print "\n$cmd is an invalid option!\n";
    }
    goto D_MONITOR_MENU;
}
###############################################################
# Diagnostic Menu Controls
###############################################################
sub proc_diag_main_menu {

    my @diag_menu = 
    (
     "Menu: Diagnostics\n",
     "-----------------\n\n",
     " [1] Loop Integrity Test (light load)\n",
     " [2] Disk Read Loop Test (heavy load)\n",
     " [3] Host Adapter Test\n",
     " [4] Disk Load Generator / Exerciser\n",
     " [5] FRU Isolation Tool (filtr)\n",
     " [6] Log File Manager\n",
     " [7] Display Last Loop Test Summary\n",
     " [8] StorEdgeDr (sedr)\n\n",
     );


#    undef @diag_menu;
            if ( defined $LITE ) {
                splice ( @diag_menu, 3, 1 );
            }
            push @diag_menu;

    push @diag_menu, " [9] Volume Manager Path Management\n" if (&cmd_exists); 

D_DIAG_MENU:
    my $cmd;
    $cmd = do_menu(\@diag_menu);
    return if ($cmd =~ /^q/i);
    if ( $cmd eq 1 )  {
        system "${BINDIR}/seqrlbf";
    } elsif ( ( $cmd eq 2 ) && ( !defined $LITE ) ) {
        system_clear();
        system "${BINDIR}/seqrlbf -read";
    } elsif ( $cmd eq 3 ) {
        system "${BINDIR}/ha_port_test";
    } elsif ($cmd eq 4) {
        system "${BINDIR}/iopmenu";
    } elsif ( $cmd eq 5 ) {
        &proc_diag_filtr_menu;
    } elsif ( $cmd eq 6 ) {
        &logfile_manage;
    } elsif ( $cmd eq 7 ) {
        &display_test_sum;
    } elsif ( $cmd eq 8 ) {
        system "${BINDIR}/sedr";
    } elsif ( $cmd eq 9 ) {
        if (&cmd_exists) {
            system "${BINDIR}/stordmp";
        } 
    } else {
        print "\n$cmd is an invalid option!\n";
    }
    goto D_DIAG_MENU;
}

###############################################################
# filtr diagnostic
###############################################################
sub proc_diag_filtr_menu {

my @ld_test_ports;
@ld_test_ports = @LD_DD_PORTS;

D_FILTR:
    system_clear();
    &st_header();
    print "Menu: FRU Isolation Tool (filtr)\n";
    print "--------------------------------\n";
    print "\n";

    print "Select a Loop to test: \n\n";
    $count = 1;
    foreach $ldport (@ld_test_ports) {
        print " [$count] ($CNUM{$ldport}) ($SOCNUM{$ldport}:Port $PORTNUM{$ldport}) ($SFNUM{$ldport}) ($ldport) ($DDCNT{$ldport} ${LUN_DISK}(s))\n";
        $count++;
    }
    print "\n";
    print " [q] Quit\n";
    print "\nEnter Choice: ";
    $portsel = &get_response;
    return if ($portsel =~ /^q/i);
    if ($portsel !~ /^\d+/) {
        print "\n$port_sel is an invalid option!\n";
    } elsif (($portsel > 0) && ($portsel <  $count)) {
        print "Testing loop: $ld_test_ports[$portsel-1]\n";
        print "This test may take a few minutes.\n\n";
        system "${BINDIR}/filtr $ld_test_ports[$portsel-1]";
        print "\n\n";
    } else {
        print "\n$port_sel is an invalid option!\n";
    }
    print "\nPress <return> for previous menu ...";
    &get_response(); 
    goto D_FILTR;
}

##############################################################
# Display the Last Test Summary (Diags)
##############################################################
sub display_test_sum {
  if ( -e $LOG_SUM) {
      system "/usr/bin/more $LOG_SUM";
  } else {
      print "\nNo test summary available\n";
  }
  print "\nPress <return> to continue ...";
  $tmp = &get_response;

}

##############################################################
# Log file Management
##############################################################
sub logfile_manage {
  my $ans = "";
  my ($x, $cnum);

  while ($ans ne "q") {
    system_clear();
    &st_header();
    print "Menu: Diagnostics Log File Manager\n";
    print "----------------------------------\n\n";
       print " [1] Display Full Loop Test Logs\n";
       print " [2] Display Failed Loop Test Results\n";
       print " [3] Display Full Host Adapter Test Logs\n";
       print " [4] Display Failed Host Adapter Test Results\n";
       print " [5] Display Disk Exerciser Logs\n";
       print " [6] Display FRU Isolation Tool Logs\n";
       print " [7] Remove Diagnostic Log Files\n";
    print "\n [q] Quit\n";
    print "\nSelect an operation to perform: ";
    $ans = &get_response;
    if ( $ans eq "1" ) {
        $cnum = "";
        while ($cnum ne "q") {
           @cur_menu = ("\nDisplay All Loop Test Logs\n",
                          "--------------------------\n\n");
           $cnum = &choose_diag_cnums("$LOGDIR/diags/t_seqrl.*");
           if ($cnum eq "none") {
                print "\nThere are no logfiles to display\n";
                print "\nPress <return> to continue...";
                $tmp = &get_response;
                $cnum = "q";
           }
           if ($cnum ne "q") {
              $cnum =~ s/all//;
              $x =  `/usr/bin/ls $LOGDIR/diags/t_seqrl.*$cnum*`;
              chomp $x;
              if ($x) {
                  system "/usr/bin/more $LOGDIR/diags/t_seqrl.*$cnum*";
              } else {
                  print "\nNo log files available\n";
              }
              print "\nPress <return> to continue...";
              $tmp = &get_response;
           }
        }
    } elsif ( $ans eq "2" ) {
        $cnum = "";
        while ($cnum ne "q") {
            @cur_menu = ("\nDisplay Failed Loop Test Results\n",
                           "--------------------------------\n\n");
            $cnum = &choose_diag_cnums("$LOGDIR/diags/t_seqrl.*");
            if ($cnum eq "none") {
                print "\nThere are no logfiles to display\n";
                print "\nPress <return> to continue...";
                $tmp = &get_response;
                $cnum = "q";
            }
            if ($cnum ne "q") {
                $cnum =~ s/all//;
                $x =  `/usr/bin/grep FAIL $LOGDIR/diags/t_seqrl.*$cnum*`;
                chomp $x;
                if ($x) {
                    system "/usr/bin/grep FAIL $LOGDIR/diags/t_seqrl.*$cnum* | more";
                } else {
                    print "\nNo failures\n";
                }
                print "\nPress <return> to continue...";
                $tmp = &get_response;
            }
        }

    } elsif ($ans eq "3") {
        # Full Host Adapter Test Logs
        $cnum = "";
        while ($cnum ne "q") {
            @cur_menu = ("\nDisplay Host Adapter Test Logs\n",
                         "--------------------------------\n\n");
            $cnum = &choose_diag_cnums("$LOGDIR/diags/ha_port_test.*");
            if ($cnum eq "none") {
                print "\nThere are no logfiles to display\n";
                print "\nPress <return> to continue...";
                $tmp = &get_response;
                $cnum = "q";
            }
            if ($cnum ne "q") {
                $cnum =~ s/all//;
                $x = `/usr/bin/ls $LOGDIR/diags/ha_port_test.*$cnum*`;
                chomp $x;
                if ($x) {
                    system "/usr/bin/more $LOGDIR/diags/ha_port_test.*$cnum*";
                } else {
                    print "\nNo log files available\n";
                }
                print "\nPress <return> to continue...";
                $tmp = &get_response;
            }
        }

    } elsif ($ans eq "4") {
        # Failed Host Adapter Test Logs
        # Full Host Adapter Test Logs
        $cnum = "";
        while ($cnum ne "q") {
            @cur_menu = ("\nDisplay Failed Host Adapter Test Results\n",
                         "------------------------------------------\n\n");
            $cnum = &choose_diag_cnums("$LOGDIR/diags/ha_port_test.*");
            if ($cnum eq "none") {
                print "\nThere are no logfiles to display\n";
                print "\nPress <return> to continue...";
                $tmp = &get_response;
                $cnum = "q";
            }
            if ($cnum ne "q") {
                $cnum =~ s/all//;
                $x = `/usr/bin/ls $LOGDIR/diags/ha_port_test.*$cnum*`;
                chomp $x;
                if ($x) {
                    system "/usr/bin/grep FAIL $LOGDIR/diags/ha_port_test.*$cnum* | /usr/bin/more";
                } else {
                    print "\nNo log files available\n";
                }
                print "\nPress <return> to continue...";
                $tmp = &get_response;
            }
        }

    } elsif ($ans eq "5") {
        $cnum = "";
        while ($cnum ne "q") {
            @cur_menu = ("\nDisplay Disk Exerciser Logs\n",
                           "---------------------------\n\n");
            $cnum = &choose_diag_cnums("$LOGDIR/diags/dex.*");
            if ($cnum eq "none") {
                print "\nThere are no logfiles to display\n";
                print "\nPress <return> to continue...";
                $tmp = &get_response;
                $cnum = "q";
            }
            if ($cnum ne "q") {
                $cnum =~ s/all//;
                $x = `/usr/bin/ls -1t $LOGDIR/diags/dex.$cnum*`;
                chomp $x;
                if ($x) {
                    $x =~ s/\n/ /g;
                    system "/usr/bin/more $x";
                } else {
                    print "\nNo log files available\n";
                }
                print "\nPress <return> to continue...";
                $tmp = &get_response;
            }
        }

    } elsif ( $ans eq "6" ) {
        $cnum = "";
        while ($cnum ne "q") {
            @cur_menu = ("\nDisplay FRU Isolation Tool Logs\n",
                           "-------------------------------\n\n");
            $cnum = &choose_diag_cnums("$LOGDIR/filtr/filtlog.*");
            if ($cnum eq "none") {
                print "\nThere are no logfiles to display\n";
                print "\nPress <return> to continue...";
                $tmp = &get_response;
                $cnum = "q";
            }

            if ($cnum ne "q") {
                $cnum =~ s/all//;
                $x = `/usr/bin/ls $LOGDIR/filtr/filtlog.$cnum*`;
                chomp $x;
                if ($x) {
                    system "/usr/bin/more $LOGDIR/filtr/filtlog.$cnum*";
                } else {
                    print "\nNo log files available\n";
                }
                print "\nPress <return> to continue...";
                $tmp = &get_response;
            }
        }

    } elsif ($ans eq "7") {
        @cur_menu = ("\nRemove logs for: \n",
                       "----------------\n\n");
        $cnum = &choose_diag_cnums("all");
        if ($cnum eq "none") {
            print "\nThere are no logfiles to remove\n";
            print "\nPress <return> to continue...";
            $tmp = &get_response;
            $cnum = "q";
        }
        if ($cnum ne "q") {
            print "\nAre you sure you want to remove $cnum diagnostic logfiles [y, <n>]?:";
            $ans2 = &get_response("n");
            if ($ans2 =~ /^y/i) {
                if ($cnum eq "all") {
                    `/usr/bin/ksh -c 'rm -f $LOGDIR/diags/*.* 2>/dev/null'`;
            print "\n$LOGDIR/diags/ cleared\n";
                    `/usr/bin/ksh -c 'rm -f $LOGDIR/filtr/*.* 2>/dev/null'`;
                    print "$LOGDIR/filtr/ cleared\n";
                } else {
                    `/usr/bin/ksh -c 'rm $LOGDIR/diags/*.*$cnum* 2>/dev/null'`;
                    print "\n$LOGDIR/diags/*.$cnum cleared\n";
                    if (! ($cnum =~ /sf/)) {
                      # don't go in here if ha_port_test logs being removed
                      `/usr/bin/ksh -c 'rm -f $LOGDIR/filtr/*.$cnum.* 2>/dev/null'`;
                      print "$LOGDIR/filtr/ cleared\n";
                    }
                }
                print "\nPress <return> to continue...";
                $tmp = &get_response;
            }
        }
    }
  }
}

#############################################################
# Choose c number from available diagnostic log file names
# It displays all it finds and then prompts the user to choose
# one.
# Returns: c#, all, or q, or none if no logs available
#############################################################
sub choose_diag_cnums {
  my $path = shift;

CHOOSE:
  @cur_menu="";
  my @allcnums = &get_diag_cnums($path);
  my $x = 0;
  my $ans;
  if (!@allcnums) {
      return "none";
  }
  foreach $cnum (@allcnums) {
     $x++;
     @cur_menu = (@cur_menu, "  [$x] $cnum\n");
  }
  @cur_menu = (@cur_menu, 
               "\n  [a] All\n", 
               "  [q] Quit\n",
               "\nSelect [ 1 - $x, all or <q> ]:");
  print @cur_menu;
  $ans = &get_response("q");
  if ($ans =~ /^q/i) { return "q"; }
  if ($ans =~ /^a/i) { return "all"; }
  if ($ans > 0)
  {  
     #check for a valid number 
     # check to make sure they don't have a number with a character on end 
     $num = $ans + 1;
     $num = $num - 1;
     if($num ne "$ans")
     {
       #invalid reponse
       print "\n$ans is an invalid option!\n";
       print "\nPress <return> to continue...";
       $tmp = &get_response;
       print "\n";

       goto CHOOSE;
    }
  }


  if ($ans < 1 or $ans > $x) {
      print "\n$ans is an invalid option!\n";
      print "\nPress <return> to continue...";
      $tmp = &get_response;
      print "\n";

      goto CHOOSE;
#      return "q";
  }

  return $allcnums[$ans - 1];
}

sub get_diag_cnums {
  my $path = shift;
  my %cnames;
  $path = "$LOGDIR/diags" if (!defined $path);
   if ($path eq "all") {
       $path = "$LOGDIR/diags";
       open CNAMES, "/usr/bin/ksh -c 'ls $path 2>&1' |";
       while (<CNAMES>) {
           chomp;
            $cnames{$1} = $cnames{$1} + 1 if /dex.*(\S\d+)\.\d+/;
            $cnames{$1} = $cnames{$1} + 1 if /ha_port_test\..*\..*\.(\S.*\d+)/;
            $cnames{$1} = $cnames{$1} + 1 if /t_seqrl.*(\D.*\d+)\.\d+/;



       }
       $path = "$LOGDIR/filtr";
       open CNAMES, "/usr/bin/ksh -c 'ls $path 2>&1' |";
       while (<CNAMES>) {
           chomp;
           $cnames{$1} = $cnames{$1} + 1 if /.*(\S\d+)\.\d+/;
       }
   } else {
       open CNAMES, "/usr/bin/ksh -c 'ls $path 2>&1' |";
       while (<CNAMES>) {
           chomp;
	   # get files that have a .c# in them
           $cnames{$1} = $cnames{$1} + 1 if /.*\.(c\d+)\.\d+/;
	   # get files that have a .n# in them
	   $cnames{$1} = $cnames{$1} + 1 if /.*\.(n\d+)\.\d+/;
	   #get files that have a .sf in them 
           $cnames{$1} = $cnames{$1} + 1 if /.*\.(sf\d+)/;
	   #get files that have a .fp in them 
           $cnames{$1} = $cnames{$1} + 1 if /.*\.(fp\d+)/;
	   #get files that have a .ifp in them 
           $cnames{$1} = $cnames{$1} + 1 if /.*\.(ifp\d+)/;
           # get offline HA loopback logs
           $cnames{$1} = $cnames{$1} + 1 if /.*\.(off\d+)/;

       }
   }
   close CNAMES;
   return sort (keys %cnames);
}

###############################################################
# Ask user if they want golden snapshot.    
# Returns  0  if user just wants to exit. 
# Returns  1  if user has asked for golden snapshot and created it 
# Returns  2  if user wants says no 
###############################################################
sub do_snap {
    ($disp) = @_;
    print "\nThis function will examine the live system and create or overwrite the \n";
    print "Configuration Snapshot File. This file is used as the baseline storage \n";

    print "configuration for use with Display Configuration and Check Current \n";
    print "Status commands and is required for these functions.\n\n";

    while ( 1 ) {
        if($disp eq "YNQ") {
            print "Create Configuration Snapshot File [<y>, n, q]?:";
        } else  {
            print "Create Configuration Snapshot File [<y>, n]?:";
        }
        $tmp = &get_response("y");
        if ($tmp =~ /^n/i) { 
            return(2)
        } elsif ($tmp =~ /^q/i) { 
            return(0);
        } elsif($tmp =~ /^y/i) {
            $result = system "${BINDIR}/storconfig -save -log -v -sc";

            return(1);
        }
        if($disp eq "YNQ") {
            print "Please enter [<y>, n, or q]:";
        } else  {
            print "Please enter [<y> or n]:";
        }
    }
}
###############################################################
# Display Configuration Menu Controls
###############################################################
sub disp_conf_menu {
    system_clear();
START:
        &st_header();
        print "Menu: Display Configuration\n";
        print "---------------------------\n\n";
        print "Configuration information can be displayed from either the\n";
        print "live system or the Configuration Snapshot File.  Displaying from \n";
        print "the file is recommended as probing the live config can take \n";
        print "about 30 seconds per array and may be disruptive.\n";

    $golden_snapshot = &get_golden_snapshot;
    if (! $golden_snapshot) {
        print "\nConfiguration Snapshot File does not exist.\n";
        $res = do_snap("YNQ"); 
        if($res == 0 ) {
            return(0);
        } elsif($res == 1) {
            goto START;
        } else {
            $live_conf = "-live"
        }
    } else {
        $cont = 1;
        while($cont) {
            print "Display live config: [y, <n>]: ";
            $tmp = &get_response("n");
            if ($tmp =~ /^n/i) {
                $live_conf = "";
                $cont = 0;
            } elsif ($tmp =~ /^y/i) {
                $live_conf = "-live";
                $cont = 0;
            } else {
                print "Please enter yes or no\n";
            }
        }
    }
    @args = ("${BINDIR}/cdmenu $live_conf");
    system(@args);
}
###############################################################
# Check the entry requirements.
#  Must be running as root.
#  
# OUTPUTS:  0   okay
#       1   not okay
###############################################################
sub check_entry_reqs {
    chomp($uname_out = `uname -a`);
    @uname_out = split(' ', $uname_out);
    $os_ver = $uname_out[2];
    print "DEBUG: OS VERSION = $os_ver \n" if ($DEBUG);
    $arch = $uname_out[4];
    print "DEBUG: ARCHITECTURE = $arch \n"  if ($DEBUG);
    $sys_plat = $uname_out[6];
    print "DEBUG: SYSTEM PLATFORM = $sys_plat \n" if ($DEBUG);
    if ($os_ver ne "5.6" & $os_ver ne "5.7" & $os_ver ne "5.8") {
        print "\tThis is not a supported OS release (2.6, 2.7 or 2.8). [$os_ver]\n";
        print "\nPress ENTER to continue or q to quit: ";
        my $ans = &get_response;
        if ( $ans =~ /^q/i ) {
            printf("Exiting stormenu...\n");
            exit 0;
        }
    }
}

###############################################################
# Process the command line inputs
###############################################################
sub proc_cli {
    my $i = 0;
    my @usage = 
    (
     "USAGE:  $PROGNAME [-s] [-t] [-c] where:\n",
     "\t   -s = short initialization (test one disk per enclosure)\n",
     "\t   -t = turn on timestamps\n",
     "\t   -c = turn on color printing\n",
     "\n",
     "$PROGNAME performs an initial test of the FCAL environment.\n",
     "The -s option should be used for large environments to expedite\n",
     "initialization.\n",
     "The -t option displays time stamps where appropriate.\n",
     "\n"
     );
    # init vars
    $SHORT_INIT = "FALSE";  # run the init checker
    $TIMEIT = "";       # no timing
    $GET_SORN = "FALSE";
    $COLOR = "OFF";
    $arg = shift @ARGV;
    while($arg) {
    if ($arg eq "-s") {
        $SHORT_INIT = "TRUE";
        $GET_SORN = "TRUE";
    } elsif ($arg =~ /[?|h]/i) {
        die @usage;
    } elsif ($arg eq "-t") {
        $TIMEIT = "TRUE";
    } elsif ($arg eq "-c") {
        $COLOR = "ON";
    } elsif ($arg eq "-st" || $arg eq "-ts" ) {
        $TIMEIT = "TRUE";
        $SHORT_INIT = "TRUE";
        $GET_SORN = "TRUE";
    } else {
        die "\n$arg is an invalid option!\n @usage";
    }
        $arg = shift @ARGV;
    }
    &set_color( $COLOR );
    if ( $COLOR eq "ON" ) {
        $COLOR_ARG = "-c";
    }
}

###############################################################
# create_snapshot -- Create the Configuration snapshot file.
###############################################################
sub create_snapshot {

    print "\nThis command will examine the live system and create or overwrite the \n";
    print "Configuration Snapshot File. This file is used as the baseline storage \n";
    print "configuration for use with Display Configuration and Check Current \n";
    print "Status commands.\n\n";
    print "All storage and fc-al loops should be online before creating the \n";
    print "Configuration Snapshot File.\n";
    print "\n",`/usr/bin/date` if ($TIMEIT);

    $result = system "${BINDIR}/storconfig -save -log -v -sc";
    print "\n",`/usr/bin/date` if ($TIMEIT);
    print "\nPress ENTER to continue: ";
    my $ans = &get_response;

    return($result/256);
}


sub checkLogDevice {

    $res = `df -k /var`;
    @a = split(/\n/ , $res);
    $a[1] =~ tr/ //s;
    @b = split(/ /, $a[1]);
    $avail = ($b[3] * 1000 );
    return($avail);
}

sub int {

    my $res;
}
