#!/bin/bash 
#
####################################################
# Copyright (c) 2025 Nagios Enterprises, LLC. All rights reserved.
####################################################
#
# DESCRIPTION: This script is used to migrate Nagios XI from a source server to a destination (sink) server.
# It performs various tasks such as setting up directories, SSH keys, checking SSH connectivity, 
# retrieving database credentials, replicating databases, transferring files, and restarting services.
#
# USAGE: ./Migrate.sh <SINKHOST>
# Example: ./Migrate.sh 192.168.0.1
#
# ARGUMENTS:
#   SINKHOST - The hostname or IP address of the destination server.
#
# FUNCTIONS:
#   usage() - Displays usage information and exits.
#   setupdirstr() - Sets up the directory structure for migration.
#   setup_ssh_key() - Generates and copies SSH keys to the destination server.
#   check_ssh() - Checks SSH connectivity to the destination server.
#   get_source_db_creds() - Retrieves database credentials from the source server.
#   get_sink_db_creds() - Retrieves database credentials from the destination server.
#   get_OS_versions() - Retrieves OS versions from both source and destination servers.
#   get_XI_versions_and_itype() - Retrieves Nagios XI versions and instance types from both servers.
#   get_DB_versions() - Placeholder for retrieving database versions.
#   is_db_offloaded() - Checks if the database is offloaded and handles accordingly.
#   replicate_database() - Replicates databases from source to destination server.
#   set_DB_passwords() - Sets database passwords on the destination server.
#   tar_xfer() - Transfers files from source to destination server.
#   version_specific_and_post_xfer() - Handles version-specific and post-transfer tasks.
#   ramdisk() - Sets up ramdisk on the destination server.
#   update_xi_sys_cfg() - Updates xi-sys.cfg file with new credentials.
#   restart_services() - Restarts necessary services on the destination server.
#   check_plugin_diffs() - Checks for differences in plugins between source and destination servers.
#   update_db_settings() - Updates database settings on the destination server.
#   failed_debug() - Collects debug information in case of failure.
#   offline_to_local() - Handles migration to a local database if offloaded.
#
# MAIN EXECUTION:
#   - Validates input arguments and user permissions.
#   - Sources necessary configuration files.
#   - Executes the defined functions in sequence to perform the migration.
#
#SINKHOST="$1" 
SINKHOST="" 
SINKROOTDBPASSWORD="" 
SINKDBVER="Unk"
SINKXIVER="Unk"
SINKOSVER=""
SINKOSID="Unk"
SINKUSER="root"
#
# Source of all of our problems  
SOURCEHOST="127.0.0.1" 
SOURCEDBVER="Unk"
SOURCEXIVER="Unk"
SOURCEOSVER=""
SOURCEOSID="Unk"

SOURCEHOSTNDOUTILSPASSWORD=""
SOURCEHOSTNAGIOSXIPASSWORD="" 
SOURCEHOSTNAGIOSQLPASSWORD=""
SOURCEROOTDBPASSWORD="" 
SOURCEHOSTDBMAINT_NAGIOSXIPASSWORD=""
NAME=""
VERSION="" 
SAMEOS="false" 
DATEDIR="migration-`date +%s`"
YORN="unk" 
MIGLOG="$DATEDIR/migration_log.txt"
DBOFFLOAD="No"

OVERWRITEDIRS="/usr/local/nagiosxi/etc /usr/local/nagiosxi/nom /usr/local/nagiosxi/var /usr/local/nagios/etc /usr/local/nagios/share /usr/local/nagios/var /usr/local/nagvis/etc /var/lib/mrtg /var/www/mrtg /etc/mrtg /etc/snmp"

NONOVERWRITEDIRS="/usr/local/nagiosxi/html /usr/local/nagiosxi/scripts /usr/local/nagiosxi/tmp /usr/local/nagios/libexec /usr/local/nagvis/ /usr/local/nrdp /usr/share/snmp/mibs " 

KEY_FILE=""

#        grep -q thing from_file 
#        if [ "$?" -eq 0 ]; then
#                printf "\n======================\n* You got that thing I sent ya \n======================\n"
#        fi
#
#  ssh  -o ConnectTimeout=30 -o ForwardX11=no "$SINKUSER"@"$SINKHOST"   



#############
usage() {
#############
printf "\n\nUsage: $0 <ip_address> [-k key_file] [-n ]\nip_address    IP address to connect to\n-k key_file   Optional path to key file\n-n Non-interactive\n\n"  
exit 1 
} # End usage 

#############
setupdirstr() {
#############
printf "\n This script should only be run in secure a directory that is owned and only accessible by root.\n\n\n"  
while [ $YORN != "yes" ]  
do 
	printf "Are you running this from a secure directory ? (yes/no): " 
	read YORN 
	if [ $YORN = "no" ] ; then
		printf "\nPlease run this script in a secured directory\n\n" 
		exit 2 
	fi
done

if [ -n "$DATEDIR" ]; then 
	mkdir "$DATEDIR" 
	chmod 700 "$DATEDIR"  
else 
	printf "\nProblem with date directory $DATEDIR\n" 	
	failed_debug
	exit 3 

fi
printf "\n====================\nStarting $MIGLOG @ `date`  \n====================\n" > "$MIGLOG" 
} # End setupdirstr 

#############
setup_ssh_key() {
#############

printf "\n====================\nStarting setup_ssh_key @ `date` \n====================\n" | tee -a "$MIGLOG"  

ssh-keygen -N '' -V "-1d:+1d" -f "$DATEDIR"/migrate_rsa

if [[ -n "$KEY_FILE" ]]; then
	cat "$DATEDIR"/migrate_rsa.pub | ssh  -o ConnectTimeout=30 -o BatchMode=yes -o ForwardX11=no -i "$KEY_FILE"  "$SINKUSER"@"$SINKHOST" "cat >> ~/.ssh/authorized_keys "
	echo "key update $?" 
else
	ssh-copy-id -i "$DATEDIR"/migrate_rsa.pub "$SINKUSER"@"$SINKHOST" 
fi 

if [ ! -f "$DATEDIR"/migrate_rsa ]; then
	printf "\n\n*** RSA key not found $DATEDIR/migrate_rsa" 
	failed_debug
	exit 4 
fi
} # End setup_ssh_key  

#############
check_ssh() {
#############

printf "\n====================\nStarting check_ssh @ `date` \n====================\n" | tee -a "$MIGLOG" 



printf "\n\n#################\nTesting SSH connectivity. Please enter your "$SINKUSER" password if prompted:\n#################\n\n" | tee -a  "$MIGLOG"
if [[ -n "$KEY_FILE" ]]; then
	ssh  -o ConnectTimeout=30 -o ForwardX11=no -i "$KEY_FILE"  "$SINKUSER"@"$SINKHOST" uname > /dev/null  
else
	ssh  -o ConnectTimeout=30 -o ForwardX11=no  "$SINKUSER"@"$SINKHOST" uname > /dev/null  
fi
        if [ "$?" -ne 0 ]; then
		printf "\n\a\n*** Unable to SSH into "$SINKHOST" as user "$SINKUSER" \n*** Check your password or keys for user "$SINKUSER" and \n*** make sure PermitRootLogin yes is defined \n*** in your sshd_config file. \n\n"
		failed_debug
		exit 5  
	fi

} # End of check_ssh 

#############
get_source_db_creds() {
#############
printf "\n====================\nStarting get_source_db_creds @ `date` \n====================\n" | tee -a  "$MIGLOG"
SOURCEHOSTNAGIOSXIPASSWORD=`cat /usr/local/nagiosxi/etc/xi-sys.cfg | grep nagiosxipass | tr -d \' | sed 's/nagiosxipass=//1'`
SOURCEHOSTNAGIOSQLPASSWORD=`cat /usr/local/nagiosxi/etc/xi-sys.cfg | grep nagiosqlpass | tr -d \' | sed 's/nagiosqlpass=//1'`
SOURCEHOSTNDOUTILSPASSWORD=`cat /usr/local/nagiosxi/etc/xi-sys.cfg | grep ndoutilspass | tr -d \' | sed 's/ndoutilspass=//1'`
SOURCEHOSTDBMAINT_NAGIOSXIPASSWORD=`cat /usr/local/nagiosxi/etc/xi-sys.cfg | grep dbmaintpass | tr -d \' | sed 's/dbmaintpass=//1'`
SOURCEROOTDBPASSWORD=`cat /usr/local/nagiosxi/etc/xi-sys.cfg | grep mysqlpass | tr -d \' | sed 's/mysqlpass=//1'`

if [ "$nagiosxipass" != "$cfg__db_info__nagiosxi__pwd" ] ; then
	printf "\n********************\n Password discrepency between xi-sys.cfg and config.inc.php for user nagiosxi \n********************\n" | tee -a  "$MIGLOG"
#	failed_debug
#	exit 52
fi

if [ "$ndoutilspass" == "$cfg__db_info__ndoutils__pwd"  ] ; then 
	printf "\n********************\n Password discrepency between xi-sys.cfg and config.inc.php for ndoutils \n********************\n" | tee -a  "$MIGLOG"
#	failed_debug
#	exit 52  
fi

if [ "$nagiosqlpass" == "$cfg__db_info__nagiosql__pwd"  ] ; then 
	printf "\n********************\n Password discrepency between xi-sys.cfg and config.inc.php for user nagiosql \n********************\n" | tee -a  "$MIGLOG"
#	failed_debug
#	exit 52  
fi

if [ "$dbmaintpass" == "$cfg__db_info__nagiosxi__dbmaint_pwd"  ] ; then
	printf "\n********************\n Password discrepency between xi-sys.cfg and config.inc.php for dbmaint \n********************\n" | tee -a  "$MIGLOG"
#	failed_debug
#	exit 52  
fi


} # End get_source_db_creds 

#############
get_sink_db_creds() {
#############
printf "\n====================\nStarting get_sink_db_creds @ `date` \n====================\n" |  tee -a  "$MIGLOG"  

scp -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST":/usr/local/nagiosxi/etc/xi-sys.cfg "$DATEDIR"/sink-etc.xi-sys.cfg

if [ ! -f "$DATEDIR"/sink-etc.xi-sys.cfg ]; then
	printf "\n\n*** Sink xi-sys.cfg not found $DATEDIR/sink-etc.xi-sys.cfg\n*** Verify you have XI installed on the new system.\n\n\n" | tee -a  "$MIGLOG" 
	failed_debug
	exit 6 
fi
#rsync -rlogc --progress -e 'ssh -i "$DATEDIR"/migrate_rsa' "$SINKUSER"@"$SINKHOST":/usr/local/nagiosxi/etc/xi-sys.cfg "$DATEDIR"/sink-etc.xi-sys.cfg
SINKHOSTNAGIOSXIPASSWORD=`cat "$DATEDIR"/sink-etc.xi-sys.cfg | grep nagiosxipass | tr -d \' | sed 's/nagiosxipass=//1'`
SINKHOSTNAGIOSQLPASSWORD=`cat "$DATEDIR"/sink-etc.xi-sys.cfg | grep nagiosqlpass | tr -d \' | sed 's/nagiosqlpass=//1'`
SINKHOSTNDOUTILSPASSWORD=`cat "$DATEDIR"/sink-etc.xi-sys.cfg | grep ndoutilspass | tr -d \' | sed 's/ndoutilspass=//1'`
SINKHOSTDBMAINT_NAGIOSXIPASSWORD=`cat "$DATEDIR"/sink-etc.xi-sys.cfg | grep dbmaintpass | tr -d \' | sed 's/dbmaintpass=//1'`
SINKROOTDBPASSWORD=`cat "$DATEDIR"/sink-etc.xi-sys.cfg | grep mysqlpass | tr -d \' | sed 's/mysqlpass=//1'`


} # End get_sink_db_creds 

#############
get_OS_versions () {
#############
printf "\n====================\nStarting get_OS_versions @ `date` \n====================\n" |  tee -a "$MIGLOG"

ssh  -o ConnectTimeout=30 -o ForwardX11=no -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "cat /etc/os-release" | grep "^ID=\|^VERSION=" > "$DATEDIR"/verinfo.sink   

if [ ! -f "$DATEDIR"/verinfo.sink ]; then
	printf "\n\n*** Sink Version information not found $DATEDIR/verinfo.sink" | tee -a  "$MIGLOG" 
	failed_debug
	exit 7 
fi

. ./$DATEDIR/verinfo.sink

SINKOSVER="$VERSION" 		
SINKOSID="$ID" 
NAME="" 
VERSION=""
if [ -z "$SINKOSID" -o -z "$SINKOSVER" ]; then 
	printf "SINKOSID or SINKOSVER zero size \n" | tee -a  "$MIGLOG" 
	failed_debug
	exit 8 
fi	

	
if [ ! -f "/etc/os-release" ]; then
	printf "\n\n\n /etc/os-release not found \n\n\n " | tee -a  "$MIGLOG" 
	failed_debug
	exit 9 
else 
	. /etc/os-release
	SOURCEOSVER="$VERSION" 		
	SOURCEOSID="$ID" 
	NAME="" 
	VERSION=""
	if [ -z "$SOURCEOSID" -o -z "$SOURCEOSVER" ]; then 
		printf "SOURCEOSID or SOURCEOSVER zero size \n" 
		failed_debug
		exit 10 
	fi	
fi

#printf "Sink $SINKOSNAME $SINKOSVER\n Source $SOURCEOSNAME $SOURCEOSVER"

if [ "$SINKOSID" == "$SOURCEOSID" -a "$SINKOSVER" == "$SOURCEOSVER"  ] ; then
	SAMEOS="true" 
fi	

#printf "\n Same ? $SAMEOS \n" 


} # End get_OS_versions 

#############
get_XI_versions_and_itype () {
#############
printf "\n====================\nStarting get_XI_versions_and_itype @ `date` \n====================\n" | tee -a "$MIGLOG"
 
scp -i "$DATEDIR"/migrate_rsa  "$SINKUSER"@"$SINKHOST":/usr/local/nagiosxi/var/xi-itype "$DATEDIR"/ >> "$MIGLOG" 2>&1   

if [ -f "$DATEDIR"/xi.info ]; then
        rm "$DATEDIR"/xi.info
fi
	ssh  -o ConnectTimeout=30 -o ForwardX11=no -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "cat /usr/local/nagiosxi/var/xiversion" > "$DATEDIR"/xi.info
	if [ ! -f "$DATEDIR"/xi.info ]; then
		printf "\n\n*** XI information not found $DATEDIR/xi.info" | tee -a  "$MIGLOG" 
		failed_debug
		exit 11
	fi
	. ./"$DATEDIR"/xi.info
	SINKXIVER="$release"

	if [ "$SINKXIVER" -lt "60000" ]; then 
	       printf "\n\n\n***** This script is only for use with 2024R1 or greater *****\n\n\n" | tee -a  "$MIGLOG"	
		failed_debug
	       exit 12 
	fi
	if [ -z "$SINKXIVER" ]; then 
		printf "SINKXIVER zero size \n"  | tee -a  "$MIGLOG"
		failed_debug
		exit 13 
	fi	
if [ ! -f "/usr/local/nagiosxi/var/xiversion" ]; then
        printf "\n\n\n /usr/local/nagiosxi/var/xiversion not found \n\n\n " | tee -a  "$MIGLOG"
	failed_debug
	exit 14
else
       	. /usr/local/nagiosxi/var/xiversion 
	SOURCEXIVER="$release"  
fi
#printf "Sink $SINKXIVER\nSource $SOURCEXIVER\n"


if [ "$SINKXIVER" != "$SOURCEXIVER" ]; then
	printf "\n\n\n\n!!! XI Version are different !!!\n*** Migration requires the *same* version of XI to be installed on both systems ***\n\n\n\n\n"
  	exit 15 	
fi
} # End get_XI_versions_and_itype 

#############
get_DB_versions () {
#############
printf "\n====================\nStarting get_DB_versions @ `date` \n====================\n" |  tee -a "$MIGLOG"
} # End get_DB_versions

#############
is_db_offloaded () {
#############
if [ ! -f "/usr/local/nagiosxi/html/config.inc.php" ]; then
        printf "\n\n\n /usr/local/nagiosxi/html/config.inc.php not found \n\n\n " | tee -a  "$MIGLOG"
	failed_debug
	exit 16 
fi
db_host=$(
    php -r '
        define("CFG_ONLY", 1);
        require_once($argv[1]);
        print(@$cfg["db_info"]["ndoutils"]["dbserver"] . "\n");
    ' \
        '/usr/local/nagiosxi/html/config.inc.php' 2>/dev/null |
    tail -1
)

echo $db_host | grep -q "localhost\|127.0.0.1" 

if [ "$?" != "0" ]; then
	DBOFFLOAD="Yes"	
	printf "\n\n*** Warning possible offloaded database observed $db_host. \n\n\a" | tee -a  "$MIGLOG" 
	YORN="unk"
	while [ $YORN != "yes" ]  
	do
       		printf "\nIt looks like you have an offloaded database. Would you like to migrate to a local database(yes/no):  " tee -a "$MIGLOG" | tee -a  "$MIGLOG"
		read YORN
        	if [ $YORN = "no" ] ; then
               		printf "\nMigration with an offloaded database is not currently supported\n\n" | tee -a  "$MIGLOG"
			failed_debug	
			exit 99 
		else	
			DBOFFLOAD="tolocal" 
		fi
	done
fi 


printf "\n====================\nStarting get_DB_versions @ `date` \n====================\n" |  tee -a  "$MIGLOG"
} # End get_DB_versions

#############
replicate_database () {
#############
printf "\n====================\nStarting replicate_database @ `date` \n====================\n" |  tee -a  "$MIGLOG"

nagiosql_dbport="3306"
ndoutils_dbport="3306"
nagiosxi_dbport="3306"

if [ -n "$cfg__db_info__nagiosql__dbserver" ]; then  
	nagiosql_dbserver="$cfg__db_info__nagiosql__dbserver"
else 
	nagiosql_dbserver="localhost"
fi

if [ -n "$cfg__db_info__nagiosxi__dbserver" ]; then  
	nagiosxi_dbserver="$cfg__db_info__nagiosxi__dbserver"	
else 
	nagiosxi_dbserver="localhost"	
fi

if [ -n "$cfg__db_info__ndoutils__dbserver" ]; then  
	ndoutils_dbserver="$cfg__db_info__ndoutils__dbserver"	
else 
	ndoutils_dbserver="localhost"	
fi


if [ -z "$cfg__db_info__nagiosql__user" -o -z "$cfg__db_info__nagiosxi__user" -o -z "$cfg__db_info__ndoutils__user" -o -z "$nagiosql_dbport" -o -z "$nagiosql_dbserver" -o -z "$nagiosxi_dbport"  -o -z "$nagiosxi_dbserver" -o -z "$ndoutils_dbport"  -o -z "$ndoutils_dbserver" ]; then

	eval $(php /usr/local/nagiosxi/scripts/import_xiconfig.php)

fi 

if [ -z "$cfg__db_info__nagiosql__user" -o -z "$cfg__db_info__nagiosxi__user" -o -z "$cfg__db_info__ndoutils__user" -o -z "$nagiosql_dbport" -o -z "$nagiosql_dbserver" -o -z "$nagiosxi_dbport"  -o -z "$nagiosxi_dbserver" -o -z "$ndoutils_dbport"  -o -z "$ndoutils_dbserver" ]; then

	printf "\n Missing variables for mysqldump\ncfg__db_info__nagiosql__user - $cfg__db_info__nagiosql__user \ncfg__db_info__nagiosxi__user $cfg__db_info__nagiosxi__user\ncfg__db_info__ndoutils__user $cfg__db_info__ndoutils__user \nnagiosql_dbport $nagiosql_dbport \nnagiosql_dbserver $nagiosql_dbserver \nnagiosxi_dbport $nagiosxi_dbport \nnagiosxi_dbserver $nagiosxi_dbserver \nndoutils_dbport $ndoutils_dbport \nndoutils_dbserver $ndoutils_dbserver \n"  
	failed_debug
	exit 86 

fi


############ ndoutils DB 
mysqldump -h "$ndoutils_dbserver" --port="$ndoutils_dbport" -u $cfg__db_info__ndoutils__user --password="$cfg__db_info__ndoutils__pwd" --add-drop-database -B $cfg__db_info__ndoutils__db | sed 's/utf8mb4_0900_ai_ci/utf8mb4_unicode_ci/g' | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "mysql -uroot -p$SOURCEROOTDBPASSWORD" 2>&1 >> "$MIGLOG" 

if [ "$?" -ne 0 ]; then
	printf "\n\a\n*** mysqldump to "$SINKUSER"@"$SINKHOST" failed for ndoutils \n\n" |  tee -a  "$MIGLOG" 
	failed_debug
	exit 86 
fi 

############ QL DB 
mysqldump  -h "$nagiosql_dbserver" --port="$nagiosql_dbport" -u $cfg__db_info__nagiosql__user --password="$cfg__db_info__nagiosql__pwd" --add-drop-database -B $cfg__db_info__nagiosql__db | sed 's/utf8mb4_0900_ai_ci/utf8mb4_unicode_ci/g' | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "mysql -uroot -p$SOURCEROOTDBPASSWORD" 2>&1 >> "$MIGLOG" 
if [ "$?" -ne 0 ]; then
	printf "\n\a\n*** mysqldump to "$SINKUSER"@"$SINKHOST" failed for nagiosql \n\n" |  tee -a  "$MIGLOG" 
	failed_debug
	exit 86 
fi 

############ XI DB 
mysqldump  -h "$nagiosxi_dbserver" --port="$nagiosxi_dbport" -u $cfg__db_info__nagiosxi__user --password="$cfg__db_info__nagiosxi__pwd" --add-drop-database -B $cfg__db_info__nagiosxi__db | sed 's/utf8mb4_0900_ai_ci/utf8mb4_unicode_ci/g' | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "mysql -uroot -p$SOURCEROOTDBPASSWORD" 2>&1 >> "$MIGLOG" 
if [ "$?" -ne 0 ]; then
	printf "\n\a\n*** mysqldump to "$SINKUSER"@"$SINKHOST" failed for nagiosxi \n\n" |  tee -a  "$MIGLOG" 
	failed_debug
	exit 86 
fi 

} # End replicate_database  

#############
set_DB_passwords () {
############# 
printf "\n====================\nStarting set_DB_passwords @ `date` \n====================\n" | tee -a "$MIGLOG"

echo "ALTER USER 'ndoutils'@'localhost' IDENTIFIED BY '$cfg__db_info__ndoutils__pwd';" | ssh  -o ConnectTimeout=30 -o ForwardX11=no -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "mysql -uroot -p$SINKROOTDBPASSWORD"
echo "ALTER USER 'nagiosxi'@'localhost' IDENTIFIED BY '$cfg__db_info__nagiosxi__pwd';" | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "mysql -uroot -p$SINKROOTDBPASSWORD"
echo "ALTER USER 'nagiosql'@'localhost' IDENTIFIED BY '$cfg__db_info__nagiosql__pwd';" | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "mysql -uroot -p$SINKROOTDBPASSWORD"
echo "ALTER USER 'dbmaint_nagiosxi'@'localhost' IDENTIFIED BY '$cfg__db_info__nagiosxi__dbmaint_pwd';" | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "mysql -uroot -p$SINKROOTDBPASSWORD"
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '$SOURCEROOTDBPASSWORD';" | ssh  -o ConnectTimeout=30 -o ForwardX11=no -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "mysql -uroot -p$SINKROOTDBPASSWORD"
 
}


#############
tar_xfer () {
#############
printf "\n====================\nStarting tar_xfer @ `date` \n====================\n" | tee -a  "$MIGLOG"
ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "find -L /usr/local/nagios/libexec -ls" > "$DATEDIR"/sink-plugins.txt 

 ssh  -o ConnectTimeout=30 -o ForwardX11=no -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" systemctl stop nagios 
tar -czhf - $NONOVERWRITEDIRS  |  ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "tar -xzvhf - --keep-old-files -C /" >> "$MIGLOG" 2>&1   
tar -czhf - $OVERWRITEDIRS |  ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "tar -xzvhf - -C /" >> "$MIGLOG" 2>&1   
if [ ! -f "/usr/local/nagiosxi/html/config.inc.php"  ]; then
        printf "\n\n\n *** /usr/local/nagiosxi/html/config.inc.php Not found. \n\n\n " | tee -a  "$MIGLOG"
	failed_debug
	exit 18
fi
scp -i "$DATEDIR"/migrate_rsa /usr/local/nagiosxi/html/config.inc.php "$SINKUSER"@"$SINKHOST":/usr/local/nagiosxi/html/config.inc.php >> "$MIGLOG" 2>&1   
if [ ! -f "/usr/local/nrdp/server/config.inc.php"  ]; then
        printf "\n\n\n *** /usr/local/nrdp/server/config.inc.php not found. \n\n\n " | tee -a  "$MIGLOG"
fi
scp -i "$DATEDIR"/migrate_rsa /usr/local/nrdp/server/config.inc.php "$SINKUSER"@"$SINKHOST":/usr/local/nrdp/server/config.inc.php >> "$MIGLOG" 2>&1   
if [ -f "$DATEDIR"/new-source.xi-sys.cfg   ]; then 
	scp -i "$DATEDIR"/migrate_rsa "$DATEDIR"/new-source.xi-sys.cfg "$SINKUSER"@"$SINKHOST":/usr/local/nagiosxi/etc/xi-sys.cfg
	scp -i "$DATEDIR"/migrate_rsa "$DATEDIR"/new-source.xi-sys.cfg "$SINKUSER"@"$SINKHOST":/usr/local/nagiosxi/var/xi-sys.cfg
fi

} # End tar_xfer 


#############
version_specific_and_post_xfer () {
#############
#
# version_specific_and_post_xfer
#

printf "\n====================\nStarting version_specific_and_post_xfer @ `date` \n====================\n" |  tee -a "$MIGLOG"

if [ -z "$SINKOSID" ]; then
        printf "Unable to determine the OS of your destination (sink) server.\nMake sure /etc/os-release reflects the correct OS\n" | tee -a  "$MIGLOG"
	failed_debug
        exit 19
fi

if [ -z "$SOURCEOSVER" ]; then
        printf "Unable to determine the OS of your source (this) server.\nMake sure /etc/os-release reflects the correct OS\n" | tee -a  "$MIGLOG"
        failed_debug
	exit 20
fi

if [ "$SINKOSID" != "$SOURCEOSID"  ]; then
        printf "\n**** Different OS $SOURCEOSID $SINKOSID \n" | tee -a  "$MIGLOG"
        ################################
        # Are we going Enterprise Linux -> Ubuntu or Debian
        ################################

        if [ "$SINKOSID" = "ubuntu"  -o "$SINKOSID" = "debian" ] && [ "$SOURCEOSID" != "debian" -a "$SOURCEOSID" != "ubuntu"  ] ; then
                printf "\n Going from EL -> Ubuntu/Debian \n" | tee -a  "$MIGLOG"
                OLDUID="`grep apache /etc/passwd | cut -f3  -d:`"
                OLDGID="`grep apache /etc/passwd | cut -f4  -d:`"
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /usr/local/ -gid $OLDGID -exec chgrp www-data {} \; "
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /usr/local/ -uid $OLDUID -exec chown www-data {} \; "
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /etc/mrtg -uid $OLDUID -exec chown www-data:nagios {} \; "
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /var/lib/mrtg -uid $OLDUID -exec chown www-data:nagios {} \; "
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /var/www/mrtg -uid $OLDUID -exec chown www-data:nagios {} \; "

		crontab -l -u apache  | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "crontab -u www-data - " 	

		tar -czf - --dereference /etc/openldap  |  ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "tar -xzvf - --keep-old-files  -C / ; cp  -nr /etc/openldap/* /etc/ldap/" >> "$MIGLOG" 2>&1
		ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /etc/openldap -uid $OLDUID -exec chown www-data:nagios {} \; "
	################################
        # Are we going Ubuntu or Debian ->  Enterprise Linux
        ################################
        elif [ "$SINKOSID" != "ubuntu"  -a "$SINKOSID" != "debian" ] && [ "$SOURCEOSID" = "debian" -o "$SOURCEOSID" = "ubuntu"  ] ; then
                printf "\n Going from Ubuntu/Debian -> EL \n" | tee -a  "$MIGLOG"
                OLDUID="`grep www-data /etc/passwd | cut -f3  -d:`"
                OLDGID="`grep www-data /etc/passwd | cut -f4  -d:`"
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /usr/local/ -gid $OLDGID -exec chgrp apache {} \; "
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /usr/local/ -uid $OLDUID -exec chown apache {} \; "
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /etc/mrtg -uid $OLDUID -exec chown apache:nagios {} \; "
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /var/lib/mrtg -uid $OLDUID -exec chown apache:nagios {} \; "
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /var/www/mrtg -uid $OLDUID -exec chown apache:nagios {} \; "

		crontab -l -u www-data  | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "crontab -u apache - "

		tar -czf - --dereference /etc/ldap  |  ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "tar -xzvf - --dereference --keep-old-files  -C / ; cp -nr /etc/ldap/* /etc/openldap" >> "$MIGLOG" 2>&1
                ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "find /etc/openldap -uid $OLDUID -exec chown apache:nagios {} \; "

	elif [ "$SINKOSID" = "ubuntu"  -o "$SINKOSID" = "debian" ] && [ "$SOURCEOSID" = "debian" -o "$SOURCEOSID" = "ubuntu"  ] ; then
		crontab -l -u www-data  | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "crontab -u www-data - " 
		tar -czf - /etc/ldap  |  ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "tar -xzvf - --keep-old-files -C /" >> "$MIGLOG" 2>&1
	else
		crontab -l -u apache  | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "crontab -u apache - " 
		tar -czf - /etc/openldap  |  ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "tar -xzvf - --keep-old-files -C /" >> "$MIGLOG" 2>&1
	
	fi
################################
# Same OS version no problem
################################
else
        printf "\nExcellent - looks like the same OS - no OS conflicts noted\n"  | tee -a  "$MIGLOG"
	################################
        # No problem they are compatible distros.   
        ################################
        if [ "$SINKOSID" = "ubuntu"  -o "$SINKOSID" = "debian" ] && [ "$SOURCEOSID" = "debian" -o "$SOURCEOSID" = "ubuntu"  ] ; then
		crontab -l -u www-data  | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "crontab -u www-data - " 
		tar -czf - /etc/ldap  |  ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "tar -xzvf - --keep-old-files -C /" >> "$MIGLOG" 2>&1
	else
		crontab -l -u apache  | ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "crontab -u apache - " 
		tar -czf - /etc/openldap  |  ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "tar -xzvf - --keep-old-files -C /" >> "$MIGLOG" 2>&1
	fi # fi for "$SINKOSNAME" = "Ubuntu"  ] || [ "$SINKOSNAME" = "Debian"

fi

scp -i "$DATEDIR"/migrate_rsa "$DATEDIR"/xi-itype "$SINKUSER"@"$SINKHOST":/usr/local/nagiosxi/var/xi-itype  >> "$MIGLOG" 2>&1

} ## End of version_specific_and_post_xfer

#############
ramdisk () {
#############
printf "\n====================\nStarting ramdisk @ `date` \n====================\n" |  tee -a "$MIGLOG"

if [ -f /usr/lib/systemd/system/ramdisk.service ]; then
    if [ "$SINKOSID" = "debian" -o "$SINKOSID" = "ubuntu" ]; then
        scp -i "$DATEDIR"/migrate_rsa /usr/lib/systemd/system/ramdisk.service "$SINKUSER"@"$SINKHOST":/lib/systemd/system/ramdisk.service
        ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl daemon-reload"
        ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl start ramdisk"
    else
        scp -i "$DATEDIR"/migrate_rsa /usr/lib/systemd/system/ramdisk.service "$SINKUSER"@"$SINKHOST":/usr/lib/systemd/system/ramdisk.service
        ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl daemon-reload"
        ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl start ramdisk"
    fi
fi
if [ -f /lib/systemd/system/ramdisk.service ]; then
    if [ "$SINKOSID" = "debian" -o "$SINKOSID" == "ubuntu" ]; then
        scp -i "$DATEDIR"/migrate_rsa /lib/systemd/system/ramdisk.service "$SINKUSER"@"$SINKHOST":/lib/systemd/system/ramdisk.service
        ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl daemon-reload"
        ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl start ramdisk "
    else
        scp -i "$DATEDIR"/migrate_rsa /lib/systemd/system/ramdisk.service "$SINKUSER"@"$SINKHOST":/usr/lib/systemd/system/ramdisk.service
        ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl daemon-reload"
        ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl start ramdisk"
    fi
fi
} # End ramdisk 


#############
update_xi_sys_cfg () {
#############
#
printf "\n====================\nStarting update_xi_sys_cfg @ `date` \n====================\n" |  tee -a "$MIGLOG"

cp "$DATEDIR"/sink-etc.xi-sys.cfg "$DATEDIR"/new-source.xi-sys.cfg
sed -i s/^nagiosxipass=\'$SINKHOSTNAGIOSXIPASSWORD\'/nagiosxipass=\'$SOURCEHOSTNAGIOSXIPASSWORD\'/g "$DATEDIR"/new-source.xi-sys.cfg
sed -i s/^nagiosqlpass=\'$SINKHOSTNAGIOSQLPASSWORD\'/nagiosqlpass=\'$SOURCEHOSTNAGIOSQLPASSWORD\'/g "$DATEDIR"/new-source.xi-sys.cfg
sed -i s/^ndoutilspass=\'$SINKHOSTNDOUTILSPASSWORD\'/ndoutilspass=\'$SOURCEHOSTNDOUTILSPASSWORD\'/g "$DATEDIR"/new-source.xi-sys.cfg
sed -i s/^dbmaintpass=\'$SINKHOSTDBMAINT_NAGIOSXIPASSWORD\'/dbmaintpass=\'$SOURCEHOSTDBMAINT_NAGIOSXIPASSWORD\'/g "$DATEDIR"/new-source.xi-sys.cfg
sed -i s/^mysqlpass=\'$SINKROOTDBPASSWORD\'/mysqlpass=\'$SOURCEROOTDBPASSWORD\'/g "$DATEDIR"/new-source.xi-sys.cfg
} # End update_xi_sys_cfg

#############
restart_services () {
#############
printf "\n====================\nStarting restart_services @ `date` \n====================\n" | tee -a  "$MIGLOG"

if [ "$DBOFFLOAD" = "Yes" ] ; then

	printf "*** It appears that you have an offloaded database\n*** Please shutdown the nagios and apache/php-fpm\n*** processes on your current system (source) before\n*** restrating your new (sink) XI server.\n" | tee -a  "$MIGLOG"
else 
	if [ "$SINKOSID" = "ubuntu"  -o "$SINKOSID" = "debian" ] ; then
		ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl restart nagios apache2 "
	else 
		ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "systemctl restart nagios httpd php-fpm "
	fi 

fi 
ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "sed -i s/'enable_notifications=1'/'enable_notifications=0'/g /usr/local/nagios/etc/nagios.cfg"
ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "/usr/local/nagiosxi/scripts/reconfigure_nagios.sh"
}

#############
check_plugin_diffs () {
#############

printf "\n====================\nStarting check_plugin_diffs @ `date` \n====================\n" | tee -a "$MIGLOG"
#ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST" "find -L /usr/local/nagios/libexec -ls" > "$DATEDIR"/sink-plugins.txt 

printf "\n\n*** Please note if you have any third party plugins \n*** they may need to be recompiled or their dependancies\n*** may need to be reinstalled or reconfigured.\n\nThe following plugins may be affected:\n" | tee -a "$MIGLOG" 
#
for I in `find -L /usr/local/nagios/libexec -print | rev | cut -f1 -d"/" | rev ` 
do
	if [ -f "$DATEDIR"/sink-plugins.txt ]; then
       	grep -q $I "$DATEDIR"/sink-plugins.txt 
       		if [ "$?" -ne "0" ]; then 
			ls -laF /usr/local/nagios/libexec/"$I" | tee -a "$MIGLOG" 
		fi
	fi 
done	

} # End of check_plugin_diffs  

#############
update_db_settings () {
#############
# written by CD 

if [ $DBOFFLOAD = "No" ]; then
    printf "\n======================\nRunning update_db_settings: Database detected as local.\n======================\n"
    MAXCONNECTIONSSQL="mysql -uroot -p$SINKROOTDBPASSWORD -e \"show variables like 'max_connections';\" | grep -E '[0-9]*' -o"
    OPENFILESLIMITSQL="mysql -uroot -p$SINKROOTDBPASSWORD -e \"show variables like 'open_files_limit';\" | grep -E '[0-9]*' -o"
    SQLMODESQL="mysql -uroot -p$SINKROOTDBPASSWORD -e \"select @@SQL_MODE;\" | grep 'STRICT_TRANS_TABLES' -o"
    GLOBALSQLMODESQL="mysql -uroot -p$SINKROOTDBPASSWORD -e \"select @@GLOBAL.SQL_MODE;\" | grep 'STRICT_TRANS_TABLES' -o"

    MAXCONNECTIONS=`ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i /root/.ssh/migrate_rsa "$SINKUSER"@"$SINKHOST" "$MAXCONNECTIONSSQL"`
    OPENFILESLIMIT=`ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i /root/.ssh/migrate_rsa "$SINKUSER"@"$SINKHOST" "$OPENFILESLIMITSQL"`
    SQLMODE=`ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i /root/.ssh/migrate_rsa "$SINKUSER"@"$SINKHOST" "$SQLMODESQL"`
    GLOBALSQLMODE=`ssh  -o ConnectTimeout=30 -o ForwardX11=no  -i /root/.ssh/migrate_rsa "$SINKUSER"@"$SINKHOST" "$GLOBALSQLMODESQL"`

    if [ "$MAXCONNECTIONS" -lt 1000 ]; then
        printf "\nConsider upping the max_connections for the database. See https://support.nagios.com/kb/article/nagios-xi-mysql-mariadb-max-connections-513.html\n"
    fi

    if [[ "$OPENFILESLIMIT" -lt 4096 ]]; then
        printf "\nConsider upping the open_files_limit for the database. See https://support.nagios.com/kb/article/nagios-xi-mysql-mariadb-max-connections-513.html\n"
    fi

    if [[ $SQLMODE == "STRICT_TRANS_TABLES" ]]; then
        printf "\nDisable STRICT_TRANS_TABLES mode. See https://support.nagios.com/kb/article/nagios-xi-strict_trans_tables-780.html\n"
    fi

    if [[ $GLOBALSQLMODE = "STRICT_TRANS_TABLES" ]]; then
        printf "\nDisable STRICT_TRANS_TABLES mode. See https://support.nagios.com/kb/article/nagios-xi-strict_trans_tables-780.html\n"
    fi

else
    printf "\n======================\nSkipping update_db_settings: Database detected as offloaded.\n======================\n"
fi

} # End update_db_settings

#############
failed_debug () {
#############

printf "\n Problem observed. Please standby. \n" 
ps -axef > "$DATEDIR"/psaef.txt
systemctl status > "$DATEDIR"/systemctl.txt 
cp /etc/os-release "$DATEDIR"/local-os-release.txt 
cp /usr/local/nagiosxi/var/xiversion "$DATEDIR"/local-xiversion 
find /usr/local/nagios -ls > "$DATEDIR"/nagios-filesystem.txt  
find /usr/local/nagiosxi -ls > "$DATEDIR"/nagiosxi-filesystem.txt  
find /etc -ls > "$DATEDIR"/etc-filesystem.txt  
find /var -ls > "$DATEDIR"/var-filesystem.txt  

tar -czvf Nagios-Migrate-Debug.tgz "$DATEDIR"    

printf "\n\n\n\n\a\n*\n*\n*\n*\n*\n****************************************************\n\n!!!! An error occurred with the migration process. !!!! \n\nPlease create a case on the Nagios Answer Hub and attach the file Nagios-Migrate-Debug.tgz: \n\nhttps://answerhub.nagios.com/support/s/\n\n****************************************************\n*\n*\n*\n*\n* \n\n\n"  
} # failed_debug 

#############
offline_to_local () {
#############
#    ssh  -o ConnectTimeout=30 -o ForwardX11=no -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "sed -i 's/$db_host/localhost/g' /usr/local/nagios/etc/ndo.cfg"
#    ssh  -o ConnectTimeout=30 -o ForwardX11=no -i "$DATEDIR"/migrate_rsa "$SINKUSER"@"$SINKHOST"  "sed -i 's/$cfg__db_info__nagiosxi__dbserver/localhost/g' /usr/local/nagiosxi/html/config.inc.php"

cat /usr/local/nagios/etc/ndo.cfg | sed s/"$db_host"/"localhost"/g > "$DATEDIR"/new.ndo.cfg 
cat /usr/local/nagiosxi/html/config.inc.php | sed s/"$cfg__db_info__nagiosxi__dbserver"/'localhost'/g > "$DATEDIR"/new.config.inc.one  
cat "$DATEDIR"/new.config.inc.one | sed s/"$cfg__db_info__nagiosql__dbserver"/'localhost'/g > "$DATEDIR"/new.config.inc.two  
cat "$DATEDIR"/new.config.inc.two | sed s/"$cfg__db_info__ndoutils__dbserver"/'localhost'/g > "$DATEDIR"/new.config.inc.three  
cat "$DATEDIR"/new.config.inc.three | sed s/'\x22user\x22 => \x27nagios\x27\x2C'/'\x22user\x22 => \x27ndoutils\x27\x2C'/g > "$DATEDIR"/new.config.inc.four   

scp -i "$DATEDIR"/migrate_rsa  "$DATEDIR"/new.ndo.cfg  "$SINKUSER"@"$SINKHOST":/usr/local/nagios/etc/ndo.cfg  
scp -i "$DATEDIR"/migrate_rsa  "$DATEDIR"/new.config.inc.four  "$SINKUSER"@"$SINKHOST":/usr/local/nagiosxi/html/config.inc.php  

} #offline_to_local

#########################
# int main 
#########################


 while [[ $# -gt 0 ]]; do
      case "$1" in
          -k)
              if [[ -z "$2" || "$2" == -* ]]; then
		      printf "\nError: -k requires the path and name of the ssh identity_file ( man 1 ssh )  \n"
	      	      usage 
	              exit 1
              fi
              shift 1 
              KEY_FILE="$1"
              shift 1 
	      printf "\n keyfile $KEY_FILE \n" 
              ;;
          -n)
		  printf "\n -n \n "  
	      YORN="yes"
	      shift 1
              ;;
          -*)
              printf "\nError: Unknown option: $1\n"
	      usage 
              exit 1
              ;;
          *)
              if [[ -z "$SINKHOST" ]]; then
                  SINKHOST="$1"
                  shift
              else
                  printf "\nError: Unexpected argument: $1\n"
	          usage 
                  exit 1
              fi
              ;;
      esac
  done
  # Validate required arguments
  if [[ -z "$SINKHOST" ]]; then
      printf "\nError: IP address or hostname is required\n"
      usage
      exit 1
  fi

if [ $UID != 0 ] ; then
        printf "\n\n\n You must run the script as root\n\n\n\a" | tee -a  "$MIGLOG"
        exit 21
fi

if [ -f /usr/local/nagiosxi/etc/xi-sys.cfg ] ; then
. /usr/local/nagiosxi/etc/xi-sys.cfg
fi 

if [ -f /usr/local/nagiosxi/scripts/import_xiconfig.php ] ; then
	eval $(php /usr/local/nagiosxi/scripts/import_xiconfig.php)
fi 


setupdirstr
check_ssh
setup_ssh_key
get_source_db_creds
get_sink_db_creds
is_db_offloaded
get_OS_versions
get_XI_versions_and_itype
get_DB_versions

if [ "$DBOFFLOAD" != "Yes" ] ; then
	set_DB_passwords
	replicate_database
fi 
update_xi_sys_cfg  
tar_xfer

if [ "$DBOFFLOAD" = "tolocal" ] ; then
	offline_to_local
fi 

check_plugin_diffs
ramdisk
version_specific_and_post_xfer
restart_services
