#!/usr/bin/expect

# 
# @HP_COPYRIGHT@
#
# HISTORY
# $NOHISTORY:$
# $EndNOHISTORY$
# 
# @(#)$RCSfile: dbcheck,v $ $Revision: 1.15 $ (HP) $Date: 2003/11/18 14:48:10 $
# 

####################################################################
# SC Database Integrity Check Tool
#
# Usage:
#
#
#
####################################################################

namespace eval dbcheck {

    #
    # Display the usage message
    #
    proc usage {} {
	puts -nonewline stderr "Usage: "
	puts stderr "$::argv0 \[options\]"
	puts stderr "Options:"
	puts stderr "  -tcl yes|no \t\t\t(default: no)"
	puts stderr "  -postevent yes|no \t\t(default: no)"
	puts stderr "  -backup yes|no \t\t(default: yes)"
	puts stderr "  -fix none|safe|all \t\t(default: none)"
	puts stderr "  -log filename \t\t(default:\
			/var/sra/dbcheck/<time>.log)"
	puts stderr "  -d database \t\t\t(default: system)"
	#@@ The next three are for testing purposes, but
	#@@ maybe I'll keep them in anyway.
	puts stderr "  -edir expect_code_directory \t(default:\
 			/usr/opt/srasysman/dbcheck/exp)"
	puts stderr "  -tdir test_directory \t\t(default:\
			/usr/opt/srasysman/dbcheck/check)"
	puts stderr "  -ddir description_directory \t(default:\
			/usr/opt/srasysman/dbcheck/desc)"
	puts stderr "  -help\t\t\t\t(prints this message)"
    }

    ############################### GLOBALS ################################
    #
    # NOTE: All global variables are named using UPPERCASE characters
    #

    ### Command options and default values
    variable EXP_DIR	/usr/opt/srasysman/dbcheck/exp ;# dbcheck source
    variable TEST_DIR 	/usr/opt/srasysman/dbcheck/check ;# the actual tests
    variable DESC_DIR	/usr/opt/srasysman/dbcheck/desc ;# description files
    variable TCL 	0		;# TCL parsable output?
    variable POSTEVENT 	0		;# post events when run?
    # The backup flag initial value (taken from command line or by default)
    # indicates if the backup must be performed. After a backup the value of
    # the flag is switched to 0 (no backup) and any subsequent calls to the
    # backup function will not perform a backup. In this way the check utility
    # performs only one backup per session (when first error is found and it
    # is necessary to apply some automatic fixes in the database content)
    variable BACKUP 	1
    variable FIX 	none		;# Fix inconsistencies? all|safe|none
    variable DATABASE 	"system"
    variable LOG_FILE	""

    ### Other global variables

    #the logging channel (this is open once per session)
    variable LOG_CHANNEL

    # GLOBAL_ERROR will be set to the most severe error returned by any test.
    # After all tests are finished, an event will be posted based on the
    # GLOBAL_ERROR value.
    # Tests will return one of the following:
    # -1 => internal error in test file - do not continue with other tests
    #  0 => no inconsistencies found
    #  1 => inconsistencies found - continue with tests
    #  2 => critical inconsistency found - do not continue with other tests
    variable GLOBAL_ERROR 0
    variable TESTFILE ""		;# filename of the test being run
    variable TEST_COUNT	0		;# number of tests attempted
    variable SUCCESSFUL_TESTS	0	;# number of tests w/out errors

    ############################## END GLOBALS ##############################

    proc load_sources {} {
	variable EXP_DIR

	# Load source code
	source ${EXP_DIR}/log.exp
	source ${EXP_DIR}/event.exp
	source ${EXP_DIR}/out_formatter.exp
	source ${EXP_DIR}/desc_mgr.exp
	source ${EXP_DIR}/scdb_loader.exp
	source ${EXP_DIR}/backup.exp
	source ${EXP_DIR}/utils.exp

	load libscdb.so
	load libscevent.so
    }

    #
    # Argument parsing helper function. Takes yes|y|no|n from the given value
    # The value of the flag is set to 0|1 depending by the arg val passed
    #
    proc getYN {flag_name arg_val} {
	upvar $flag_name flag
	switch -- [string tolower $arg_val] {
	    "yes" 	{set flag 1}
	    "y"		{set flag 1}
	    "no"	{set flag 0}
	    "n"		{set flag 0}
	    default {
		usage
		set msg "-[string tolower $flag_name] option must be "
		set msg "$msg followed by yes|no|y|n"
		puts stderr $msg
		exit -1
	    }
	}
    }

    #
    # This procedure loads and launches a test script
    # The file_name parameter is the name of the script
    # Returns: 
    #   -1  if there was some internal error (file not found or syntax)
    #    0  if test found no inconsistencies found
    #    1  if test found inconsistencies
    #    2  if test found a critical inconsistency and testing should stop
    #
    proc run_test { file_name } {
	variable GLOBAL_ERROR 
	variable TEST_COUNT
	variable SUCCESSFUL_TESTS
	variable FIX
	variable TEST_DIR
	variable DESC_DIR
	variable LOG_FILE
	variable DATABASE
	variable TESTFILE
	variable TCL

	incr TEST_COUNT

	log "run_test: Test \#$TEST_COUNT"
	log "run_test: Running tests in $file_name"
	if {!$TCL} {
	    puts -nonewline stdout "Test \#${TEST_COUNT} "
	    flush stdout
	}

	# check to see if the file exists
	if {![file exists $file_name]} {
	    set msg "Cannot load test file: $file_name. File does not exist."
	    log "run_test: $msg"
	    post_error "$file_name does not exist\nSee log file $LOG_FILE"
	    return -1
	}
	# Compute the test name. The test name is used as the 
	# namespace name to assure that procedures don't clash.
	# The test name is the test file name without the "Tnnn."
	# prefix.  Example: file /usr/opt/sra/check/T010.attrib_check
	# the test name/namespace name is check.
	set file_tail [file tail $file_name]
	set test_name [lindex [split $file_tail "."] 1]

	# Each test file should have a function called main. Since
	# it is in a different namespace, it must be called with
	# a prefix:
	set main_func "${test_name}::main"

	# Source in the test file in its own namespace
	set err [catch {
	    # Can't access file_name from within the new
	    # namespace so have to use TESTFILE.  Yuck!
	    set TESTFILE $file_name
	    namespace eval $test_name {
		source ${::dbcheck::TESTFILE}
	    }
	} ret]

	if {$err} {
	    log "run_test: Error loading $file_name."
	    log "          - stack trace follows\n$::errorInfo"
	    set msg "Error loading $file_name"
	    post_error "$msg\nSee log file $LOG_FILE"
	    return -1
	}

	# Run the test! 
	if {[catch {info procs $main_func}]} {
	    log "run_test: File $file_name has not defined proc main."
	    set msg "File $file_name has not defined proc main."
	    post_error "$msg\nSee log file $LOG_FILE"
	    return -1
	} 

	log "run_test: Calling $main_func"
	if { [catch {eval $main_func $FIX $DESC_DIR} ret] } {
	    log "run_test: Error evaluating $main_func."
	    log "	   - stack trace follows\n$::errorInfo"
	    set msg "Error evaluting $main_func from file $file_name"
	    post_error "$msg\nSee log file $LOG_FILE"
	    return -1
	}

	# depending on what main_func returned, we may want to exit right away
	switch "x$ret" {
	    "x-1" {
		log "run_test: $main_func returned -1: INTERNAL ERROR"
		log "run_test: Further testing aborted."
		set msg "Internal error in $file_name. "
		set msg "$msg Further testing aborted."
		post_error "$msg\nSee log file $LOG_FILE"
		exit -1
	    }
	    "x0" {
		log "run_test: $main_func returned 0: no inconsistencies found"
		# do not post event or exit; wait until all tests are run
		# but let user know it succeeded
		if {!$TCL} {
		    puts stdout "passed"
		    flush stdout
		}
	    }
	    "x1" {
		set GLOBAL_ERROR 1
		log "run_test: $main_func returned 1: inconsistencies found"
		# do not post event or exit; wait until all tests are run
		# but print a pretty separator
		if {!$TCL} {
		    puts stdout "*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~"
		    flush stdout
		}
	    }
	    "x2" {
		set msg "$main_func returned 2: CRITICAL INCONSISTENCIES FOUND"
		log "run_test: $msg"
		log "run_test: Further testing aborted."
		set msg "Critical inconsistencies found by $file_name."
		set msg "$msg\nFurther testing aborted."
		post_fail "$msg\nSee log file $LOG_FILE"
		exit 2
	    }
	}

	incr SUCCESSFUL_TESTS
	return 0
    }

    ########################### MAIN PROCEDURE ############################
    proc main {} {
	variable TCL
	variable POSTEVENT
	variable BACKUP
	variable FIX
	variable LOG_FILE
	variable DATABASE
	variable EXP_DIR
	variable TEST_DIR
	variable DESC_DIR
	variable TEST_COUNT
	variable SUCCESSFUL_TESTS
	variable GLOBAL_ERROR

	#parse arguments and set the options flags
	for {set i 0} {$i < [llength $::argv]} {incr i} {
	    switch -- [lindex $::argv $i] {
		"-tcl" {
		    #next argument shold be yes|no|y|n
		    incr i
		    getYN TCL [lindex $::argv $i]
		}
		"-postevent" {
		    incr i
		    getYN POSTEVENT [lindex $::argv $i]
		}
		"-backup" {
		    incr i
		    getYN BACKUP [lindex $::argv $i]
		}
		"-fix" {
		    #next argument is necessary to be none|safe|all or n|s|a
		    incr i
		    switch -- [string tolower [lindex $::argv $i]] {
			"none"	{set FIX none}
			"n"	{set FIX none}
			"safe"	{set FIX safe}
			"s"	{set FIX safe}
			"all"	{set FIX all}
			"a"	{set FIX all}
			default {
			    usage
			    set msg "-fix option must be followed by"
			    set msg "$msg none|safe|all or n|s|a"
			    puts stderr $msg
			    exit -1
			}
		    }
		}
		"-log" {
		    #next argument is the log file name
		    incr i
		    if {"[lindex $::argv $i]" != "" &&
			[string index [lindex $::argv $i] 0] != "-"} {
			set LOG_FILE [lindex $::argv $i]
		    } else {
			usage
			set msg "-log option must be followed by the name"
			puts stderr   "$msg of the log file"
			exit -1
		    }
		}
		"-database" {
		    #next argument should be the database name
		    incr i
		    if {"[lindex $::argv $i]" != "" &&
			[string index [lindex $::argv $i] 0] != "-"} {
			set DATABASE [lindex $::argv $i]
		    } else {
			usage
			set msg "-database option must be followed by the"
			puts stderr   "$msg database name"
			exit -1
		    }
		}
		"-edir" {
		    #next argument is the directory where the
		    #dbcheck source can be found
		    incr i
		    if {"[lindex $::argv $i]" != "" &&
			[string index [lindex $::argv $i] 0] != "-"} {
			set EXP_DIR [lindex $::argv $i]
		    } else {
			usage
			set msg "-edir option must be followed by a"
			puts stderr "$msg directory name"
			exit -1
		    }
		}
		"-tdir" {
		    #next argument is the directory where the
		    #tests can be found
		    incr i
		    if {"[lindex $::argv $i]" != "" &&
			[string index [lindex $::argv $i] 0] != "-"} {
			set TEST_DIR [lindex $::argv $i]
		    } else {
			usage
			set msg "-tdir option must be followed by a"
			puts stderr "$msg directory name"
			exit -1
		    }
		}
		"-ddir" {
		    #next argument is the directory where the
		    #descriptions can be found
		    incr i
		    if {"[lindex $::argv $i]" != "" &&
			[string index [lindex $::argv $i] 0] != "-"} {
			set DESC_DIR [lindex $::argv $i]
		    } else {
			usage
			set msg "-ddir option must be followed by a"
			puts stderr "$msg directory name"
			exit -1
		    }
		}

		"-help" { usage; exit 0 }

		"-?"	{ usage; exit 0 }

		default {
		    usage
		    puts stderr "[lindex $::argv $i] is an invalid option"
		    exit -1
		}
	    }
	}

	if { [ catch {load_sources} msg ] } {
	    puts stderr "Could not load dbcheck source files from $EXP_DIR."
	    puts stderr "Try using the -edir command line argument."
	    exit -1
	}

	## Open the log file if the name of the log file is not specified
	## then the log file will be open in /var/sra/adm/log/dbcheck/
	if {$LOG_FILE != ""} {
	    open_custom_log $LOG_FILE
	} else {
	    open_default_log
	}

	log "*** Starting database integrity check ***"
	log "dbcheck: ============== testing parameters =============="
	log "dbcheck: = command line: $::argv0 $::argv"
	log "dbcheck: = working directory: [pwd]"
	log "dbcheck: = dbcheck source directory: $EXP_DIR"
	log "dbcheck: = test directory: $TEST_DIR"
	log "dbcheck: = description directory: $DESC_DIR"
	log "dbcheck: = log file: $LOG_FILE"
	log "dbcheck: = TCL output: $TCL"
	log "dbcheck: = post events: $POSTEVENT"
	log "dbcheck: = backup db: $BACKUP"
	log "dbcheck: = fix db: $FIX"
	log "dbcheck: = database: $DATABASE"
	log "dbcheck: ================================================"

	######################################################################
	##
	##                            START OF TESTS
	##
	## The tests are TCL or expect scripts stored in TEST_DIR (defaults to
	## /usr/opt/sra/check).  Each file name should be of the following 
	## form:
	##     T<nnn>.<name>.<extension>
	## where <nnn> is a 3 digit number, <name> is the name of the test and
	## .<extension> is optional.  For example, T010.attribute_check.tcl or
	## T010.attribute_check are both valid test file names.  All other 
	## files are ignored. The tests will be run in numeric order based on
	## the value of <nnn>. So T010.attribute_check.tcl will be run before
	## T020.sra_config.tcl.
	## 
	## The <name> part of the test file name is also used to determine the
	## description file name.  It will be of the form <name>_desc.tcl and
	## can be found in the description directory.
	## 
	## Each file must provide a main procedure called main.  The procedure
	## must take two arguments.  The first argument be the fix type: all,
	## safe or none (fix all errors, just the safe ones, or none at all).
	## The second argument is the directory where the description files
	## can be found.
	## 
	## NOTE: All the test scripts can access and change the global 
	## variables. Also
	## the caching of the database tables is global and the script test is 
	## responsible for loading and unloading cached results(tables). 
	## 
	log_user 0				;# don't echo spawn output
	spawn -noecho ls -1 $TEST_DIR		;# get a list of files

	set done 0
	while {!$done} {
	    expect {
		-re {T[0-9][0-9][0-9]\.[^\n]+} { # look for files named Tnnn.* 
		    set testfile [string trim $expect_out(0,string)]
		    run_test $TEST_DIR/$testfile ;# Run the test
		}

		{eof} { set done 1 }		;# end loop on EOF
	    }
	}

	if {$TEST_COUNT == 0} {

	    # This should be brought to the user's attention.  It
	    # probably is just a matter of specifying -tdir.

	    set GLOBAL_ERROR -1
	}

	## Some final messages and logging
	set how_many "$SUCCESSFUL_TESTS tests out of $TEST_COUNT run"
	log "dbcheck: ====> $how_many"
	log "dbcheck: ====> Highest severity: $GLOBAL_ERROR"

        switch -exact "x$GLOBAL_ERROR" {
	    x0 {
		set msg "dbcheck finished -- there were no inconsistencies"
		log "dbcheck: ====> $msg"
		post_attention "$msg\n$how_many\nSee log file $LOG_FILE"
		set exit_value 0
	    }
	    x1 {
		set msg "dbcheck finished -- inconsistencies were found"
		log "dbcheck: ====> $msg"
		post_warning "$msg\n$how_many\nSee log file $LOG_FILE"
		set exit_value 1
	    }
	    x-1 {
		log "dbcheck! No tests were run!"
		puts stderr "No tests found in $TEST_DIR."
		puts stderr "Try using the -tdir command line argument."
		post_error "No tests found in $TEST_DIR."
		set exit_value -1
	    }
	    default {
		# This should never happen -- see run_test
		set msg "dbcheck finished with an unexpected error value:"
		set msg "$msg $GLOBAL_ERROR"
		log "dbcheck: Unexpected GLOBAL_ERROR after all tests complete"
		log "dbcheck: ====> $msg"
		post_error "$msg\n$how_many\nSee log file $LOG_FILE"
		set exit_value -1
	    }
	}

	log "*** Database integrity check finished ***"
	close_log

	exit $exit_value
    }
}

## Run dbcheck
dbcheck::main
