#!/bin/sh
#############################################################################
#
# Licensed Materials - Property of IBM
# IBM DB2 Net Search Extender Version 9.5
# Product Number 5724-E49, 5765-F35, 5765-F41, 5724-N76, 5724-B55
#  COPYRIGHT International Business Machines Corp. 2006, 2007
#
# All Rights Reserved.
#
# US Government Users Restricted Rights - Use, duplication or
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
#
#############################################################################

#
# NAME: db2extimigr
#
# FUNCTION: db2extimigr - migrate the DB2 Net Search Extender part of a DB2 instance
#                         for a previous version of DB2 to the current version.
#
# USAGE: db2extimigr [-h|-?] InstName
#          -h|-?         display the usage information.
#          InstName      is the name of the instance.
#
#############################################################################
# Options for "set" command
setopts="${setopts:-+x}"
set ${setopts?}

# Current DB2 installation directory

curdir=`/bin/pwd`
DB2DIR=`dirname $0`
cd ${DB2DIR?}
DB2DIR=`/bin/pwd`
cd ${DB2DIR?}
DB2DIR=`dirname ${DB2DIR?}`
cd ${curdir?}
unset curdir

# Set the directory name where this file is located.
curdir=`/bin/pwd`
PROGDIR=`dirname $0`
cd ${PROGDIR?}
PROGDIR=`/bin/pwd`
cd ${curdir?}

PROGNAME=`basename $0`       # Program name
PROCID=$$
NSEIMIGLOG="/tmp/${PROGNAME?}.log.${PROCID?}"   # DB2 log file
if [ -f /sbin/mount ]; then
    MOUNT=/sbin/mount
else
    MOUNT=mount
fi
if [ -f /sbin/umount ]; then
    UMOUNT=/sbin/umount
else
    UMOUNT=umount
fi


#-----------------------------------------------------------------------#
#               Start of function definitions
#-----------------------------------------------------------------------#

# To display the help menu
help()
{
    echo 'Usage: '${PROGNAME?}' [-h|-?] InstName'
    exit 1
}

# Write to log file
nseilog()
{
    set ${setopts?}
    echo $* >> ${NSEIMIGLOG?}
}

# Check if root is running the prog
chk_root()
{
    set ${setopts?}

    nseilog 'Checking if root is running the program'
    if [ `${DB2DIR?}/bin/db2usrinf -E` -ne 0 ]; then
        echo 'You must be root to execute this program.' | tee -a ${NSEIMIGLOG?}
        exit 1
    fi
}

# Find the home dir for given user ID. Set environment variable USERHOME
# Parameters: $1: the name of the user
find_homedir()
{
    set ${setopts?}

    nseilog 'Retrieving home directory of user '${1?}
    
    username=$1

    # is the user valid?
    if ${DB2DIR?}/bin/db2usrinf -q ${username?}
    then
        USERHOME=`${DB2DIR?}/bin/db2usrinf -d ${username?}`
        nseilog 'Home directory of user '${username?}' is '${USERHOME?}
    else
        echo 'The user ID '${username?}' is invalid.' | tee -a ${NSEIMIGLOG?} 
        stop_prog 1
    fi

    return 0
}

# stop_prog - exit
# Parameters: $1: the exit code
stop_prog()
{
    set ${setopts?}

    nseilog 'stop_prog called with exit code '${1?}
    
    sig=${1:-1}

    if [ ${sig?} -eq 1 ]; then
        echo 'Program '${PROGNAME?}' terminated unexpectedly.'  | tee -a ${NSEIMIGLOG?}
        echo 'Please view the log file '${NSEIMIGLOG?}' for details.'
    fi
    if [ ${sig?} -eq 0 ]; then
        echo 'Program '${PROGNAME?}' completed successfully.'  | tee -a ${NSEIMIGLOG?}
    fi
     
    exit ${sig?}
}


# look for old sqllib as the source of the migration
get_old_sqllib()
{
    set ${setopts?}
    
    nseilog 'Check for old sqllib'
    index_dir=db2ext/indexes
    if [ -d ${USERHOME?}/sqllib_v81 ]; then
        check_if_empty ${USERHOME?}/sqllib_v81/${index_dir}
        if [ ${empty?} = "no" ]; then
            OLDSQLLIB=sqllib_v81
        fi
    fi
    if [ -d ${USERHOME?}/sqllib_v91 ]; then
        check_if_empty ${USERHOME?}/sqllib_v91/${index_dir}
        if [ ${empty?} = "no" ]; then
            OLDSQLLIB=sqllib_v91
        fi
    fi
    if [ -d ${USERHOME?}/sqllib_v95 ]; then
        check_if_empty ${USERHOME?}/sqllib_v95/${index_dir}
        if [ ${empty?} = "no" ]; then
            OLDSQLLIB=sqllib_v95
        fi
    fi
    if [ ${OLDSQLLIB?} = "" ]; then
        echo "No old sqllib directory could be found."  | tee -a ${NSEIMIGLOG?}
        nseilog 'Checked for sqllib_v81, sqllib_v91'
        stop_prog 1
    fi
    nseilog 'Old sqllib is: '${OLDSQLLIB?}
}

# retrieve the size of a directory in kbytes
# Parameters: $1: the name of the directory
# Result:     size: the size of the directory in kbytes
get_dir_size()
{
    set ${setopts?}
    size=`du -ks $1 | awk '{print $1}'`
    nseilog 'Directory size of '${1?}'='${size?}' kbytes'
}

# retrieve the size of a file in bytes
# Parameters: $1: the name of the file
# Result:     size: the size of the file in kbytes (rounded up)
get_file_size()
{
    set ${setopts?}
    size=`ls -l ${1?} | awk '{print $5}'`
    if [ ${size?} -ne 0 ]; then
        size=`expr ${size?} / 1024`
        size=`expr ${size?} + 1`
    else
        size=1       # minimum size
    fi
    nseilog 'File size of '${1?}'='${size?}' kbytes'
}

# retrieve the free space of a filesystem in kbytes
# Parameter: $1: the directory which is part of the filesystem
# Result:    free_space_in_fs: the free space of the filesystem in kbytes 
get_fs_size()
{
    set ${setopts?}
    if [ ${OPSYSTEM?} != 'HP-UX' ]; then
        fs_name="`df -k ${1?} | sed -n '2 p' | awk '{print $1}'`"
        output_df="`df -k  ${1?} | sed -n '$ p'`"
        free_space_in_fs=`echo ${output_df?} | awk '{if ($4 !~ /%/) {print $4} else {print $3}}'`
    else # we have a HP operating system with a different df -k output
        fs_name="`df -k ${1?} | sed -n '1 p' | awk '{print $1}'`"
        output_df="`df -k  ${1?} | sed -n '2 p'`"
        free_space_in_fs=`echo ${output_df?} | awk '{print $1}'`
    fi
    nseilog 'Free space of file system '${fs_name?}': '${free_space_in_fs?}' kbytes'
}

# calculate the new free space of a file system if the size of an object is
# subtracted
# Parameters: $1: the name of the file system of which the subtraction is done
#             $2: the size of the subtraction
#             $3: the name of the file system which is to be checked
#             $4: the old free space of the file system which is to be checked
# Result:     new_size: the new free space of the file system which is to be checked
# Example: Assuming that for the file system /dev/sda3 200 kbytes are needed and
#          for another purpose the reduced free space information is needed. So
#          $1=/dev/sda3 $2=200 $3=/dev/sda3 $4=500000 -> new_size=499800
#          $1=/dev/sda3 $2=200 $3=/dev/sda6 $4=500000 -> new_size=500000
#          
decrement_if_necessary()
{
    set ${setopts?}
    nseilog 'Decrement_if_necessary parameters:'
    nseilog '$1='${1?}'    $2='${2?}
    nseilog '$3='${3?}'    $4='${4?}
    fs_to_reduce=$1
    size_to_reduce=$2
    test_fs=$3
    test_size=$4
    # if the file systems are identical
    if [ ${fs_to_reduce?} = ${test_fs?} ]; then
        new_size=`expr ${test_size?} - ${size_to_reduce?}`
    else
        new_size=${test_size?}
    fi
    nseilog 'Decrement free space of file system '${test_fs?}' to '${new_size?}
    
}

#  copy object (directory or file)
#  Parameters: $1: source for move operation
#              $2: target for move operation
copy_obj()
{
    set ${setopts?}
    
    nseilog 'Copying '${1?}' to '${2?}
    cp -p ${1?} ${2?}
    if [ $? -ne 0 ]; then
        echo 'Copying '${1?}' to '${2?}' failed' | tee -a ${NSEIMIGLOG?}
        stop_prog 1
    fi
}

#  check if a directory is empty
#  Parameters: $1: the name of the directory
#  Result:     empty ("yes"/"no")
check_if_empty()
{
    set ${setopts?}
    
    if [ `ls ${1?} | wc -l ` -lt 1 ]; then
        empty="yes"
    else
        empty="no"
    fi
    
    nseilog 'Checking if directory '${1?}' is empty. Result: '${empty?}
}

# get device info of a directory
# Parameters: $1: the name of the directory
# Results:     device_name
#              device_is_local
get_device_info()
{
    set ${setopts?}
    
    mount_output=`${MOUNT?} | grep ${1?} 2>&1`
    
    if [ $? -eq 0 ]; then
        # handle different output of mount command
        case ${OPSYSTEM?} in
            "Linux")
                device_name=`echo ${mount_output?} | awk '{ print $1 }'`
                number_of_fields=`echo ${device_name?} | awk 'BEGIN { FS = ":" } ; { print NF }'`
                if [ ${number_of_fields?} -eq 1 ]; then
                    device_is_local="yes"
                else 
                    device_is_local="no"
                fi
                ;;
            "SunOS")
                device_name=`echo ${mount_output?} | awk '{ print $3 }'`
                number_of_fields=`echo ${device_name?} | awk 'BEGIN { FS = ":" } ; { print NF }'`
                if [ ${number_of_fields?} -eq 1 ]; then
                    device_is_local="yes"
                else
                    device_is_local="no"
                fi
                ;;
            "AIX")
                # AIX mount output format:
                # <node> <mounted> <mounted over> <vfs> <date (3 fields)> <options>
                # NF from awk = 8 -> $2
                # <node> can be empty -> NF != 8 -> $1
                device_name=`echo ${mount_output?} | awk '{if (NF = 8) {print $2} else {print $1}}'`;
                number_of_fields=`echo {mount_output?} | awk ' { print NF }'`
                if [ ${number_of_fields?} -eq 8 ]; then
                    node=`echo {mount_output?} | awk ' { print $1 }'`
                    host=`uname -n`
                    if [ ${node?} = ${host?} ]; then
                        device_is_local="yes"
                    else
                        device_is_local="no"
                    fi
                else
                    device_is_local="yes"
                fi
                ;;
            *)
                echo 'Operating system '${OPSYSTEM?}' not supported. Reading mount output failed.' | tee -a ${NSEIMIGLOG?}
                stop_prog 1
                ;;
        esac
   fi
}

# migrate directory depending on the type
# Parameters: $1: the name of the directory
#             $2: the type (direct/link/mount)
migrate_dir()
{
    set ${setopts?}
    
    migDir=$1
    dirType=$2
    
    nseilog 'Migrating directory '${migDir?}' of type '${dirType?}
    
    case ${dirType?} in
        "link")
            # remove the new dir if empty and set new link
            check_if_empty ${USERHOME?}/sqllib/${migDir?}
            if [ ${empty?} = "yes" ]; then
                nseilog 'Remove new directory '${migDir?}
                rmdir ${USERHOME?}/sqllib/${migDir?}
                if [ $? -eq 0 ]; then
                    link_target=`ls -l ${USERHOME?}/${OLDSQLLIB?}/${migDir?} | awk '{print $(NF) }'`
                    ln -s ${link_target?} ${USERHOME?}/sqllib/${migDir?}
                    if [ $? -ne 0 ]; then
                        echo 'Linking directory '${link_target?}' to '${USERHOME?}/sqllib/${migDir?}' failed.' | tee -a ${NSEIMIGLOG?}
                        stop_prog 1
                    fi
                else
                    echo 'Removing '${USERHOME?}/sqllib/${migDir?}' failed.' | tee -a ${NSEIMIGLOG?}
                    stop_prog 1
                fi
            else
                echo 'Cannot remove '${USERHOME?}/sqllib/${migDir?}' because it is not empty.' | tee -a ${NSEIMIGLOG?}
                stop_prog 1
            fi
            nseilog 'New link for '${USERHOME?}/sqllib/${migDir?}' successfully done.'
            ;;
        "mount")
            # get device name and check if file system is local
            get_device_info ${USERHOME?}/${OLDSQLLIB?}/${migDir?}
            deviceName=${device_name?}
            if [ ${device_is_local?} = "yes" ]; then
                # try to unmount
                nseilog 'Unmounting '${USERHOME?}/${OLDSQLLIB?}/${migDir?}
                ${UMOUNT?} ${USERHOME?}/${OLDSQLLIB?}/${migDir?} 1>/dev/null 2>&1
                if [ $? -eq 0 ]; then
                    nseilog 'Mount '${deviceName?}' to '${USERHOME?}/sqllib/${migDir?}
                    ${MOUNT?} ${deviceName?} ${USERHOME?}/sqllib/${migDir?}
                    if [ $? -eq 0 ]; then
                        # notice to the user to modify fstab
                        echo 'Mounting '${deviceName?}' to '${USERHOME?}/sqllib/${migDir?}' was successful.' | tee -a ${NSEIMIGLOG?}
                        echo 'The /etc/fstab file should also be updated accordingly.' | tee -a ${NSEIMIGLOG?}
                    else
                        echo 'Could not ${MOUNT?} '${deviceName?}' to '${USERHOME?}/sqllib/${migDir?} | tee -a ${NSEIMIGLOG?}
                        stop_prog 1
                    fi
                else
                    echo 'Could not unmount '${deviceName?}'.' | tee -a ${NSEIMIGLOG?}
                    stop_prog 1
                fi
            else
                echo 'Remote directory mounted. Cannot proceed.' | tee -a ${NSEIMIGLOG?}
                stop_prog 1
            fi
            ;;
        "direct")
            # check if it is empty
            check_if_empty ${USERHOME?}/${OLDSQLLIB?}/${migDir?}
            if [ ${empty?} = "no" ]; then
                # copy stuff over to new location
                nseilog 'Copying content of '${USERHOME?}/${OLDSQLLIB?}/${migDir?}' to '${USERHOME?}/sqllib/${migDir?} 
                cp -pr ${USERHOME?}/${OLDSQLLIB?}/${migDir?}/* ${USERHOME?}/sqllib/${migDir?}
                if [ $? -eq 0 ]; then
                    # remove it from old location
                    nseilog 'Remove content of '${USERHOME?}/${OLDSQLLIB?}/${migDir?}
                    rm -rf ${USERHOME?}/${OLDSQLLIB?}/${migDir?}/*
                    if [ $? -ne 0 ]; then
                        echo 'Removing old files of '${USERHOME?}/${OLDSQLLIB?}/${migDir?}' failed.' | tee -a ${NSEIMIGLOG?}
                        stop_prog 1
                    fi
                else
                    echo 'Copy of '${USERHOME?}/${OLDSQLLIB?}/${migDir?}' failed.' | tee -a ${NSEIMIGLOG?}
                    stop_prog 1
                fi
            fi
            ;;
         *)
            echo 'Invalid directory type for '${USERHOME?}/${OLDSQLLIB?}/${migDir?} | tee -a ${NSEIMIGLOG?}
            ;;
    esac
}

#  Checks if a directory contains an own file system
#  Parameters: $1: the name of the directory
#  Result:     mounted: indicates that the directory contains an own file system
check_for_mount()
{
    set ${setopts?}
    
    mount_output=`${MOUNT?} | grep ${1?} 2>&1`
    if [ $? -eq 0 ]; then
        # handle different output of mount command
        case ${OPSYSTEM?} in
            "Linux")
                mdir=`echo ${mount_output?} | awk '{ print $3 }'`
                ;;
            "SunOS")
                mdir=`echo ${mount_output?} | awk '{ print $1 }'`
                ;;
            "AIX")
                # AIX special format see function get_device_name()
                mdir=`echo ${mount_output?} | awk '{if ( NF = 8 ) { print $3 } else { print $2 }}' `;
                ;;
            *)
                echo 'Operating system '${OPSYSTEM?}' not supported. Reading mount output failed.' | tee -a ${NSEIMIGLOG?}
                stop_prog 1
                ;;
        esac
        if [ ${mdir?} = ${1?} ]; then
            mounted="yes"
        else # only a subdirectory
            mounted="no"
        fi
    else
        mounted="no"
    fi
    nseilog 'Check if '${1?}' contains own file system. Result: '${mounted?}
}

#  Determine the directory type and its size
#  Parameter: $1: the name of the directory
#             $2: the name of the variable for the directory type
#             $3: the name of the variable for the directory size
#  If the directory contains an own file system or is a link the size will be
#  set to 0
determine_directory_type_and_size()
{
    set ${setopts?}
    
    if [ -h ${1?} ]; then
        # link does not need much space
        type="link"
        size=0
    else 
        # check if it is a mounted file system
        check_for_mount $1
        if [ ${mounted?} = "yes" ]; then
            type="mount"
            size=0
        else
            type="direct"
            get_dir_size $1
        fi
    fi
    eval ${2?}=${type?}
    eval ${3?}=${size?}
    nseilog 'Determing type of directory '${1?}'. Result '${type?}' is set in '${2?}
    nseilog 'Determing size of directory '${1?}'. Result '${size?}' is set in '${3?}
}

#-----------------------------------------------------------------------#
#                End of function definitions
#-----------------------------------------------------------------------#

#-----------------------------------------------------------------------#
#                             Main program
#-----------------------------------------------------------------------#

chk_root           # Check that only root is running this program

# Process command-line options
case $# in
    0)
        help ;;
    1)
        INSTNAME="$1"            # Instance name
        if [ -z "${INSTNAME?}" ]; then
            help
        fi ;;
    *)
        help ;;
esac

set ${setopts?}
echo "Migrating instance "$INSTNAME" for DB2 Net Search Extender"  | tee -a ${NSEIMIGLOG?}

# check if there is a sqllib_v81 directory
#---------------------------------------------------------------------
# Sets the environment variable INSTHOME - home directory of INSTNAME.
#---------------------------------------------------------------------
OPSYSTEM=`uname`
find_homedir ${INSTNAME?}
INSTHOME=${USERHOME?}
get_old_sqllib

# get type of directories (link/mount/direct) and size
determine_directory_type_and_size ${USERHOME?}/${OLDSQLLIB?}/db2ext/indexes "INDEX_DIR_TYPE" "INDEX_DIR_SIZE"
determine_directory_type_and_size ${USERHOME?}/${OLDSQLLIB?}/db2ext/memory "MEMORY_DIR_TYPE" "MEMORY_DIR_SIZE"
determine_directory_type_and_size ${USERHOME?}/${OLDSQLLIB?}/db2ext/thes "THES_DIR_TYPE" "THES_DIR_SIZE"

# get size of configuration files
get_file_size ${USERHOME?}/${OLDSQLLIB?}/db2ext/ctedem.dat
DEM_FILE_SIZE=${size?}
get_file_size ${USERHOME?}/${OLDSQLLIB?}/db2ext/cteixcfg.ini
IXCFG_FILE_SIZE=${size?}
get_file_size ${USERHOME?}/${OLDSQLLIB?}/db2ext/db2extlm.cfg
EXTLM_FILE_SIZE=${size?}

# check if filesystem size of new directory is sufficient
get_fs_size ${USERHOME?}/sqllib/db2ext/indexes
INDEX_FS_SIZE=${free_space_in_fs?}
INDEX_FS_NAME=${fs_name?}
get_fs_size ${USERHOME?}/sqllib/db2ext/memory
MEM_FS_SIZE=${free_space_in_fs?}
MEM_FS_NAME=${fs_name?}
get_fs_size ${USERHOME?}/sqllib/db2ext/thes
THES_FS_SIZE=${free_space_in_fs?}
THES_FS_NAME=${fs_name?}
get_fs_size ${USERHOME?}/sqllib/db2ext
DB2EXT_FS_SIZE=${free_space_in_fs?}
DB2EXT_FS_NAME=${fs_name?}

# doing some calculations
if [ ${INDEX_FS_SIZE?} -gt ${INDEX_DIR_SIZE?} ]; then
    decrement_if_necessary ${INDEX_FS_NAME?} ${INDEX_DIR_SIZE?} ${MEM_FS_NAME?} ${MEM_FS_SIZE?}
    MEM_FS_SIZE=${new_size?}
    decrement_if_necessary ${INDEX_FS_NAME?} ${INDEX_DIR_SIZE?} ${THES_FS_NAME?} ${THES_FS_SIZE?}
    THES_FS_SIZE=${new_size?}
    decrement_if_necessary ${INDEX_FS_NAME?} ${INDEX_DIR_SIZE?} ${DB2EXT_FS_NAME?} ${DB2EXT_FS_SIZE?}
    DB2EXT_FS_SIZE=${new_size?}
else
    echo "Insufficient disk space to migrate index directory."  | tee -a ${NSEIMIGLOG?}
    stop_prog 1
fi

if [ ${MEM_FS_SIZE?} -gt ${MEMORY_DIR_SIZE?} ]; then
    decrement_if_necessary ${MEM_FS_NAME?} ${MEMORY_DIR_SIZE?} ${THES_FS_NAME?} ${THES_FS_SIZE?}
    THES_FS_SIZE=${new_size?}
    decrement_if_necessary ${MEM_FS_NAME?} ${MEMORY_DIR_SIZE?} ${DB2EXT_FS_NAME?} ${DB2EXT_FS_SIZE?}
    DB2EXT_FS_SIZE=${new_size?}
else
    echo "Insufficient disk space to migrate memory directory."  | tee -a ${NSEIMIGLOG?}
    stop_prog 1
fi

if [ ${THES_FS_SIZE?} -gt ${THES_DIR_SIZE?} ]; then
    decrement_if_necessary ${THES_FS_NAME?} ${THES_DIR_SIZE?} ${DB2EXT_FS_NAME?} ${DB2EXT_FS_SIZE?}
    DB2EXT_FS_SIZE=${new_size?}
else
    echo "Insufficient disk space to migrate thesaurus directory."  | tee -a ${NSEIMIGLOG?}
    stop_prog 1
fi

if [ ${DB2EXT_FS_SIZE?} -gt ${DEM_FILE_SIZE?} ]; then
    DB2EXT_FS_SIZE=`expr ${DB2EXT_FS_SIZE?} - ${DEM_FILE_SIZE?}`
else
    echo "Insufficient disk space to migrate demon file."  | tee -a ${NSEIMIGLOG?}
    stop_prog 1
fi

if [ ${DB2EXT_FS_SIZE?} -gt ${IXCFG_FILE_SIZE?} ]; then
    DB2EXT_FS_SIZE=`expr ${DB2EXT_FS_SIZE?} - ${IXCFG_FILE_SIZE?}`
else
    echo "Insufficient disk space to migrate index configuration file."  | tee -a ${NSEIMIGLOG?}
    stop_prog 1
fi

if [ ${DB2EXT_FS_SIZE?} -le ${EXTLM_FILE_SIZE?} ]; then
    echo "Insufficient disk space to migrate lock manager file."  | tee -a ${NSEIMIGLOG?}
    stop_prog 1
fi  


# move files and directories (if not empty)
migrate_dir db2ext/indexes ${INDEX_DIR_TYPE?}
migrate_dir db2ext/memory ${MEMORY_DIR_TYPE?}
migrate_dir db2ext/thes ${THES_DIR_TYPE?}

if [ -f ${USERHOME?}/${OLDSQLLIB?}/db2ext/ctedem.dat ]; then
    copy_obj ${USERHOME?}/${OLDSQLLIB?}/db2ext/ctedem.dat ${USERHOME?}/sqllib/db2ext
fi
if [ -f ${USERHOME?}/${OLDSQLLIB?}/db2ext/cteixcfg.ini ]; then
    copy_obj ${USERHOME?}/${OLDSQLLIB?}/db2ext/cteixcfg.ini ${USERHOME?}/sqllib/db2ext
fi
if [ -f ${USERHOME?}/${OLDSQLLIB?}/db2ext/db2extlm.cfg ]; then
    copy_obj ${USERHOME?}/${OLDSQLLIB?}/db2ext/db2extlm.cfg ${USERHOME?}/sqllib/db2ext
fi

stop_prog 0
