#!/bin/ksh93
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# 61haes_r720 src/43haes/usr/sbin/cluster/haws/sbin/subsys/db2/import.sh 1.22 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2004,2015 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# @(#)27	1.22 src/43haes/usr/sbin/cluster/haws/sbin/subsys/db2/import.sh, hacmp.assist, 61haes_r720, 1539B_hacmp720 9/11/15 17:33:12
#
###############################################################################
#
# This script performed the low-level task of importing the DB2
# configuration into HACMP.

# DB2 Package name
DB2_PACKAGE_NAME="db2_08_01.db2.engn"

# Version variables
DB2_VERSION_81="8.1"
DB2_VERSION=""

# The directory where DB2 is installed
DB2_INSTALL_DIR=""

# The volume group where DB2 is configured. We'll need to make sure
# this is made highly available.
DB2_VG=""

# Specifies the name of the node where DB2 will fallover to.
DB2_FALLOVER_NODE=""

# Specifies the instance home and name
DB2_INSTANCE_HOME=""
DB2_INSTANCE_NAME=""
DB2_DATABASE_NAME=""

# Specified thed default installation directory
DB2_DEFAULT_INSTALL_DIR="/usr/opt/db2_08_01"
DB2_DEFAULT_DATABASE="sample"

#
###############################################################################
#
# SCRIPT DEFINITION SECTION
#
###############################################################################
# Define Functions
#
# This section should be used to define functions used by this script.
# The following functions are defined:
#
# verify_db2_version - Verifies that the DB2 version is
#                            at the correct level.
#
# get_db2_install_dir - Find the websphere installation directory. 
#                             This function will also determine the vg
#                             that websphere is installed under.
#
# parse_db2_config - Parses the websphere configuration files and
#                          loads internal variables
#
# validate_db2_config - This name is a little misleading. What it
#                             does is to make sure the Websphere config
#                             files contain nodes that are defined in
#                             hacmp. It will peform other checks too, but
#                             the intent is to make sure the import process
#                             will work.
# generate_import_script - Generate the actual script that will be used
#                          to import db2 configuration information
#                          into hacmp
###############################################################################

###############################################################################
# Function: verify_db2_version
###############################################################################
#
# Make sure that DB2 is at version 8.1.1
###############################################################################
verify_db2_version() {
    logmsg HAWS_DEBUG "$MSG_DEBUG_MSG" "Checking DB2 version..."
    DB2_VERSION=$(lslpp -Lc $DB2_PACKAGE_NAME 2>/dev/null | sed -e '/^#/d' | cut -f3 -d':' | cut -f 1,2 -d '.')
    logmsg HAWS_DEBUG  "$MSG_DEBUG_MSG" "DB2 Version = $DB2_VERSION\n"
    
    case $DB2_VERSION in
	$DB2_VERSION_81)
	    logmsg HAWS_INFO "$MSG_DB2_VER81_DETECTED" "IBM DB2 UDB v8.1 detected\n"
	    ;;
	"")
	    logmsg HAWS_ERROR "$MSG_DB2_NOT_INSTALLED" "IBM DB2 UDB could not be found.  Please install IBM DB2 UDB v8.1\n"
	    exit $HAWS_EXIT_FAIL
	    ;;
	*)
	    logmsg HAWS_ERROR "$MSG_DB2_UNKNOWN_VERSION" "Unsupported version of DB2 UDB: %s.  Please install IBM DB2 UDB v8.1\n" $DB2_VERSION
	    exit $HAWS_EXIT_FAIL
    esac
}

###############################################################################
# Function: get_db2_install_dir
###############################################################################
#
# It doesn't seem possible to figure out where DB2 is installed
# by looking at the results from lslpp. We'll have to hardcode this
# location for now. Keep this function in place though just in case
# we are able to programmtically figure out where the darn thing is
# installed.
###############################################################################
get_db2_install_dir() {
    logmsg HAWS_DEBUG  "$MSG_DEBUG_MSG" "Getting db2 installation directory..."
    if [[ -z $DB2_INSTALL_DIR ]]
    then
	DB2_INSTALL_DIR=$DB2_DEFAULT_INSTALL_DIR
    fi
    logmsg HAWS_DEBUG  "$MSG_DEBUG_MSG" "Directory = $DB2_INSTALL_DIR"
}


###############################################################################
# Function: parse_db2_config
###############################################################################
# Get the DB2 Instance Directory.  This should be on a shared volume group
###############################################################################
parse_db2_config() {
    DB2_INSTANCE_DIR=$(lsuser -a home $DB2_INSTANCE_NAME | cut -d'=' -f2)

    logmsg HAWS_DEBUG "$MSG_DEBUG_MSG" "DB Directory = $DB2_INSTANCE_DIR"
}

###############################################################################
# Function: get_db2_vg
###############################################################################
#
# We need to figure out where our filesystem is located. For now, force
# the user to pass this information into us.
###############################################################################
get_db2_vg() {
    logmsg HAWS_DEBUG  "$MSG_DEBUG_MSG" "Getting the vg for DB2 Database Instance: $DB2_INSTANCE_DIR\n" 
    VG=""
    if [[ -d "$DB2_INSTANCE_DIR" ]] ; then
	findvg $DB2_INSTANCE_DIR"/sqllib"
	if (( $? == $HAWS_EXIT_FAIL ))
	then
	    exit $HAWS_EXIT_FAIL
	fi
	DB2_VG=$VG
    fi

    if [[ -z $DB2_VG ]]
    then
	logmsg HAWS_ERROR "$MSG_DB2_UNKNOWN_VG" "Can't get the volume group for DB2 directory: %s\n" $DB2_INSTANCE_HOME
	exit $HAWS_EXIT_FAIL
    fi
    logmsg HAWS_INFO  "$MSG_DB2_VG_FOUND" "DB2 Volume group = %s\n" $DB2_VG
}

###############################################################################
# Function: validate_db2_config
###############################################################################
#
# Validate the DB2 configuration information against HACMP. Make
# sure it makes sense to import this stuff.
###############################################################################
validate_db2_config() {
    logmsg HAWS_DEBUG  "$MSG_DEBUG_MSG" "Validating DB2 configuration..."

    DB2NODES=$(/usr/bin/su - $DB2_INSTANCE_NAME "-c echo \\${VWSPATH}/db2nodes.cfg")
    if [[ -z $(grep -w "$DB2_SERVICE_LABEL" "$DB2NODES") ]] ; then
	logmsg HAWS_WARN "$MSG_DB2_WARN_DB2NODESCFG" "The supplied PowerHA SystemMirror service label (%s) is not found in the db2nodes.cfg.\n" $DB2_SERVICE_LABEL
    fi

    DB2RHOSTS=$(/usr/bin/su - $DB2_INSTANCE_NAME "-c echo \\${HOME}/.rhosts")
    if [[ ! -f "$DB2RHOSTS" ]] ; then
	logmsg HAWS_WARN "$MSG_DB2_WARN_DB2RHOSTS" "Missing .rhosts file for %s.\n" $DB2_INSTANCE_NAME
    fi

    #Try to ping database.
    if ! /usr/bin/su - $DB2_INSTANCE_NAME -c "db2 connect to $DB2_DATABASE_NAME" > /dev/null 2>&1
    then
	logmsg HAWS_WARN $MSG_DB2_MON_CONNECT_FAILED "Unable to connect to the database: %s.\n" $DB2_DATABASE_NAME
	logmsg HAWS_WARN $MSG_DB2_NOT_ACCESSIBLE "If database %s cannot be accessed, application monitoring will fail.\n" $DB2_DATABASE_NAME
    else
	logmsg HAWS_TRACE $MSG_DB2_MON_CONNECT_SUCCEEDED "Connected to the database: %s.\n" $DB2_DATABASE_NAME
	if ! /usr/bin/su - $DB2_INSTANCE_NAME -c "db2 ping $DB2_DATABASE_NAME" > /dev/null 2>&1
	then
	    logmsg HAWS_WARN $MSG_DB2_MON_PING_FAILED "Unable to ping the database: %s.\n" $DB2_DATABASE_NAME
	    logmsg HAWS_WARN $MSG_DB2_NOT_ACCESSIBLE "If database %s cannot be accessed, application monitoring will fail.\n" $DB2_DATABASE_NAME
	else
	    logmsg HAWS_TRACE $MSG_DB2_MON_PING_SUCCEEDED "Ping'ed the database: %s.\n" $DB2_DATABASE_NAME
	fi
	/usr/bin/su - $DB2_INSTANCE_NAME -c "db2 disconnect $DB2_DATABASE_NAME" > /dev/null 2>&1
    fi

    # If not Validating, there is no need to do anything else.
    if (( $VALIDATE_FLAG != 1 )) ; then
	return
    fi

    # Check for the configuration file
    logmsg HAWS_DEBUG $MSG_DEBUG_MSG "Checking Configuration file $cfg_script"
    if [[ ! -f $cfg_script ]] ; then
	logmsg HAWS_ERROR $MSG_CONFIG_FILE_NOT_FOUND "The configuration file %s was not found.\n" $cfg_script
	return
    fi

    # Check the Configuration script for matching items
    logmsg HAWS_DEBUG $MSG_DEBUG_MSG "Checking DB2_INSTANCE_DIR $DB2_INSTANCE_DIR"
    if [[ -z $(grep -w "DB2_INSTANCE_DIR=$DB2_INSTANCE_DIR" $cfg_script) ]] ; then
	logmsg HAWS_ERROR $MSG_DB2_NO_MATCH_INSTANCE_DIR "The DB2 Instance Directory %s does not match value in %s\n" $DB2_INSTANCE_DIR $cfg_script
    fi

    logmsg HAWS_DEBUG $MSG_DEBUG_MSG "Checking DB2_INSTANCE_NAME $DB2_INSTANCE_NAME"
    if [[ -z $(grep -w "DB2_INSTANCE_NAME=$DB2_INSTANCE_NAME" $cfg_script) ]] ; then
	logmsg HAWS_ERROR $MSG_DB2_NO_MATCH_INSTANCE_NAME "The DB2 Instance Name %s does not match value in %s\n" $DB2_INSTANCE_NAME $cfg_script
    fi

    logmsg HAWS_DEBUG $MSG_DEBUG_MSG "Checking DB2_DATABASE_NAME $DB2_DATABASE_NAME"
    if [[ -z $(grep -w "DB2_DATABASE_NAME=$DB2_DATABASE_NAME" $cfg_script) ]] ; then
	logmsg HAWS_ERROR $MSG_DB2_NO_MATCH_DATABASE_NAME "The DB2 Database Name %s does not match value in %s\n" $DB2_DATABASE_NAME $cfg_script
    fi
}

###############################################################################
# Function: generate_import_script
###############################################################################
#
# Write the script that will be used to import the db2 configuration
# information into HACMP.
###############################################################################
generate_import_script() {

    # Setup the variable names here
    db2_start_script="$HAWS_HOME/sbin/subsys/db2/startDB2"
    db2_stop_script="$HAWS_HOME/sbin/subsys/db2/stopDB2"
    db2_monitor_script="$HAWS_HOME/sbin/subsys/db2/monitor_db2"

    # This is the script that does the actual import
    logmsg HAWS_TRACE  "$MSG_CREATE_IMPORT" "Generating the import script...\n"

    echo "#!/bin/sh" > $create_script
    echo "# Script Automatically created on $(date)" >> $create_script
    echo "# Any changes made to this file will be lost next time" >> $create_script
    echo "# the DB2 UDB configuration information is imported" >> $create_script
    echo " " >> $create_script
    echo ". $clhaws_functions" >> $create_script
    echo " " >> $create_script

    echo "get_cluster_state" >> $create_script
    echo "if [[ \$CLUSTER_STATE -ne 0 ]] ; then" >> $create_script
    echo "logmsg HAWS_ERROR $MSG_CLUSTER_NOT_STABLE \"Cluster is not in stable state.\\\\n\"" >> $create_script
    echo "exit 1" >> $create_script
    echo "fi" >> $create_script
    echo " " >> $create_script

    echo "# Create the application server " >> $create_script
    echo "$CLADDSERV -s'$asname' -b'$db2_start_script $cfg_script' -e'$db2_stop_script $cfg_script'" >> $create_script
    echo "logmsg HAWS_INFO $MSG_APP_SERVER_CREATED \"Application Server %s created.\\\\n\" \"$asname\"" >> $create_script
    echo " " >> $create_script

    echo "# Create the resource group " >> $create_script
    echo "$CLADDGRP -g '$rgname' -s 'ignore' -n '$(hostname) $DB2_FALLOVER_NODE' -S 'OHN' -O 'FNPN' -B 'FBHPN'" >> $create_script
    echo "logmsg HAWS_INFO $MSG_RESOURCE_GROUP_CREATED \"Resource Group %s created.\\\\n\" \"$rgname\"" >> $create_script
    echo " " >> $create_script

    echo "# Create the application monitor" >> $create_script
    echo "$CLADDAPPMON MONITOR_TYPE=user name='$asname' INVOCATION='$mon_mode' RESOURCE_TO_MONITOR='$asname' MONITOR_METHOD='$app_monitor_script' MONITOR_INTERVAL='120' STABILIZATION_INTERVAL='240' RESTART_COUNT='3' RESTART_INTERVAL='1440' FAILURE_ACTION='fallover' CLEANUP_METHOD='$db2_stop_script $cfg_script' RESTART_METHOD='$db2_start_script $cfg_script' HUNG_MONITOR_SIGNAL='9'" >> $create_script
    echo "logmsg HAWS_INFO $MSG_APP_MON_CREATED \"Application Monitor for application server %s created.\\\\n\" \"$asname\"" >> $create_script
    echo " " >> $create_script

    echo "# Create the resource to monitor now" >> $create_script
    echo "$CLADDRES -g '$rgname' APPLICATIONS='$asname' VOLUME_GROUP='$DB2_VG' SERVICE_LABEL='$DB2_SERVICE_LABEL'" >> $create_script
    echo "logmsg HAWS_INFO $MSG_RESOURCES_CREATED \"Resources added to resource group %s.\\\\n\" \"$rgname\"" >> $create_script
    echo " " >> $create_script

    echo "logmsg HAWS_INFO $MSG_IMPORT_CREATE_COMPLETE \"%s import create complete.\\\\n\" DB2" >> $create_script
    echo " " >> $create_script

    # This is the script that backs out the changes
    logmsg HAWS_TRACE  "$MSG_CREATE_REMOVE" "Generating the remove script...\n"

    echo "#!/bin/sh" > $delete_script
    echo "# Script Automatically created on $(date)" >> $delete_script
    echo "# Any changes made to this file will be lost next time" >> $delete_script
    echo "# the DB2 UDB configuration information is imported" >> $delete_script
    echo " " >> $delete_script
    echo ". $clhaws_functions" >> $delete_script
    echo " " >> $delete_script

    echo "get_cluster_state" >> $delete_script
    echo "if [[ \$CLUSTER_STATE -ne 0 ]] ; then" >> $delete_script
    echo "logmsg HAWS_ERROR $MSG_CLUSTER_NOT_STABLE \"Cluster is not in stable state.\\\\n\"" >> $delete_script
    echo "exit 1" >> $delete_script
    echo "fi" >> $delete_script
    echo " " >> $delete_script

    echo "# Remove the resources " >> $delete_script
    echo "$CLRMRES -g '$rgname'" >> $delete_script
    echo "logmsg HAWS_INFO $MSG_RESOURCES_DELETED \"Resources removed to resource group %s.\\\\n\" \"$rgname\"" >> $delete_script
    echo " " >> $delete_script

    echo "# Remove the application monitor " >> $delete_script
    echo "$CLRMAPPMON $asname" >> $delete_script
    echo "logmsg HAWS_INFO $MSG_APP_MON_DELETED \"Application Monitor for application server %s deleted.\\\\n\" \"$asname\"" >> $delete_script
    echo " " >> $delete_script

    echo "# Remove the application server " >> $delete_script
    echo "$CLRMSERV $asname" >> $delete_script
    echo "logmsg HAWS_INFO $MSG_APP_SERVER_DELETED \"Application Server %s deleted.\\\\n\" \"$asname\"" >> $delete_script
    echo " " >> $delete_script

    echo "# Remove the resource group " >> $delete_script
    echo "$CLRMGRP -g $rgname" >> $delete_script
    echo "logmsg HAWS_INFO $MSG_RESOURCE_GROUP_DELETED \"Resource Group %s deleted..\\\\n\" \"$rgname\"" >> $delete_script
    echo " " >> $delete_script

    echo "logmsg HAWS_INFO $MSG_IMPORT_DELETE_COMPLETE \"%s import delete complete.\\\\n\" WAS" >> $delete_script
    echo " " >> $delete_script

    # Create the configuration script where application specific settings are stored
    logmsg HAWS_TRACE  "$MSG_CREATE_CONFIG" "Generating config file...\n"

    echo "#!/bin/sh" > $cfg_script
    echo "# Script Automatically created on $(date)" >> $cfg_script
    echo "# Any changes made to this file will be lost next time" >> $cfg_script
    echo " " >> $cfg_script

    echo "DB2_INSTANCE_DIR=$DB2_INSTANCE_DIR" >> $cfg_script
    echo "DB2_INSTANCE_NAME=$DB2_INSTANCE_NAME" >> $cfg_script
    echo "DB2_DATABASE_NAME=$DB2_DATABASE_NAME" >> $cfg_script

    echo "#!/bin/sh" > $app_monitor_script
    echo "# Script Automatically created on $(date)" >> $app_monitor_script
    echo "# Any changes made to this file will be lost next time" >> $app_monitor_script
    echo "# the DB2 UDB configuration information is imported" >> $app_monitor_script
    echo " " >> $app_monitor_script
    echo "# DB2 UDB monitor script " >> $app_monitor_script
    echo " " >> $app_monitor_script
    echo "$db2_monitor_script \"$cfg_script\"" >> $app_monitor_script
    echo " " >> $app_monitor_script
    echo "exit \$?" >> $app_monitor_script

    complete_scripts $DB2_FALLOVER_NODE
}


###############################################################################
#
# Function: process_arguments
# This is a subsystem-specific version of the routine that processes
# command line arguments. 
#
#   -i Specifies the instance home directory
#   -n Specified the fallover node
###############################################################################
process_arguments() {
    logmsg HAWS_DEBUG "$MSG_DB2_PROCARG" "Processing 'db2' arguments...\n"

    while getopts :i:n:d:l: c 
      do 
        case $c in
         i) DB2_INSTANCE_NAME=$OPTARG
            logmsg HAWS_INFO "$MSG_DB2_INST_NAME_SET" "DB2 Instance Name is specified as %s\n" $DB2_INSTANCE_NAME
	    ;;
         n) DB2_FALLOVER_NODE=$OPTARG
            logmsg HAWS_INFO "$MSG_FALLOVER_NODE_NAME_SET" "Fallover Node specified as %s\n" $DB2_FALLOVER_NODE
	    ;;
         d) DB2_DATABASE_NAME=$OPTARG
            logmsg HAWS_INFO "$MSG_DB2_DATABASE_NAME_SET" "DB2 database name set to %s\n" $DB2_DATABASE_NAME
	    ;;
	 l) DB2_SERVICE_LABEL=$OPTARG
	    logmsg HAWS_INFO "$MSG_SERVICE_LABEL_SET" "Service Label set to %s\n" $DB2_SERVICE_LABEL
	    ;;
        \?)
	    logmsg HAWS_ERROR "$MSG_UNKNOWN_OPTION" "Unrecognized command line option specified\n"
            exit $HAWS_EXIT_FAIL;;   
         esac 
      done 

    logmsg HAWS_DEBUG "$MSG_DB2_PROCDONE" "Done processing 'db2' arguments...\n";

    status=0

    # Make sure that a fallover node was specified
    if [[ -z $DB2_FALLOVER_NODE ]]
    then
	logmsg HAWS_ERROR "$MSG_NO_FALLOVER" "You must specify a fallover node using the -n flag\n"
	status=1
    fi

    # Make sure that a service label was specified
    if [[ -z $DB2_SERVICE_LABEL ]]
    then
	logmsg HAWS_ERROR "$MSG_NO_SERVICE_LABEL" "You must specify a service label using the -l flag\n"
	status=1
    fi

    # Make sure that an instance name was specified
    if [[ -z $DB2_INSTANCE_NAME ]]
    then
	logmsg HAWS_ERROR "$MSG_DB2_NO_INST_NAME" "You must specify an instance name using the -i flag\n"
	status=1
    fi

    # Make sure that a database was specified. If not, then default
    # to the "SAMPLE" database
    if [[ -z $DB2_DATABASE_NAME ]]
    then
	logmsg HAWS_INFO "$MSG_DB2_USING_DEFAULT_DB" "No database specified. Using default database: %s\n" $DB2_DEFAULT_DATABASE
	DB2_DATABASE_NAME=$DB2_DEFAULT_DATABASE
    fi

    if (( status != 0 ))
    then
	exit $HAWS_EXIT_FAIL
    fi
}


###############################################################################
#
# SCRIPT EXECUTION SECTION
#
###############################################################################
# This section of the script is used to call into the various predefined
# to perform the actual script execution.
#
# The intent of this section is to provide a high-level view of how this
# script operates.
###############################################################################
process_arguments $*

verify_db2_version
parse_db2_config
get_db2_vg
create_script_names "db2" $DB2_INSTANCE_NAME"_"$(hostname) $DB2_FALLOVER_NODE
validate_db2_config

# If not Validating, generate the scripts
if (( $VALIDATE_FLAG != 1 ))
then
    generate_import_script
fi


