#!/bin/sh
# Copyright (c) 2002-2008 by Rack-Soft, LLC
# Copyright (c) 2002-2008 by 4PSA (www.4psa.com)
# All rights reserved

# This script installs or update 4PSA DNS Manager on supported operating systems


is_root()
{
current_user="`id`"
case "$current_user" in
	uid=0\(root\)*)
	;;
	*)
		echo "$0: You must have root privileges in order to install ${product_name}"
		echo "Su as root and try again"
		echo
		exit 1
	;;
esac
}


die()
{
	echo "ERROR: $*"
	echo "Check the error reason, fix and try again"
	echo 
	exit 1
}


download_yuminf()
{
	rm -f yum.inf
	${wget_path}wget -T20 ${dsite}/${REPO}/yum.inf >/dev/null 2>&1
	if [ -f yum.inf ];then
		yum_location=`grep "^${sys}${release}" yum.inf | awk '{print $2}'`
		yumconf_location=`grep "^${sys}${release}" yum.inf | awk '{print $3}'`
		if [ -z ${yum_location} -o -z ${yumconf_location} ];then
			echo
			die "The remote repository does not contain information for this OS!"
		fi
	else
		die "Could not get the yum information file."
	fi
}


download_yum()
{
echo -n "==> Installing yum package manager, please stand-by... "

	download_yuminf
	
	${wget_path}wget -T20 ${dsite}${yum_location} >/dev/null 2>&1
	if [ -f `basename ${yum_location}` ];then
		rpm -Uv `basename ${yum_location}`
		if [ $? -eq 0 ];then
			echo 'Done!'
		else
			echo
			echo "Could not install yum RPM package." 
			die "Please solve the dependencies manually and re-execute installer."
		fi
	else
		die "Could not get yum RPM package."
	fi
}


import_4psa_key()
{
	rpm --import http://www.4psa.com/software/4PSA-GPG-KEY
}


check_yum()
{
which yum >/dev/null 2>&1
if [ $? -gt 0 ];then
	# yum is not in path
	rpm -q yum >/dev/null 2>&1
	if [ $? -gt 0 ];then
		#yum must be downloaded and installed
		download_yum
	else
		#yum seems installed, but not in path
		if [ -f /usr/bin/yum ];then
			#yum was found in /usr/bin
			yum_path='/usr/bin/'
		else
			echo "The RPM package manager yum is installed on your system, but ${product_name} installer can not find it."
			die "It's not in the system PATH or in a standard location"
		fi
	fi
fi
}


check_wget()
{
which wget >/dev/null 2>&1
if [ $? -gt 0 ];then
	if [ -f /usr/bin/wget ];then
		wget_path='/usr/bin/'
	else
		echo "wget binary can not be found."
		die "It's not in the system PATH or in a standard location."
	fi
fi
}


get_yumconf()
{
	download_yuminf
	rm -f dnsmanager-yum.conf
	
	${wget_path}wget -T20 ${dsite}${yumconf_location} >/dev/null 2>&1
	if [ ! -f dnsmanager-yum.conf ];then
		die "Could not get dnsmanager-yum.conf"
	fi
}

remove_conflicts()
{
	echo
	echo "==> Trying to remove unwanted packages that conflict with ${product_name} ..."

	yum -y -c dnsmanager-yum.conf remove bind-chroot

	if [ ! -f /usr/local/dnsmanager/.version ];then
		echo
		echo "==> Trying to remove old mysql-server (if present)..."
	    
		[ -f "/etc/init.d/mysqld" ]&& sh /etc/init.d/mysqld stop
		killall -9 mysqld_safe  2>/dev/null
		killall -9 mysqld 2>/dev/null
		rpm -qa | grep -i "mysql" | grep -i "server" | xargs rpm -e  2> /dev/null
		[ -f "/etc/my.cnf" ] && mv /etc/my.cnf /etc/my.cnf.save	
		if  [ "`rpm -qa |grep -i mysql |grep -ic server`" = "0" ];then
			echo "Sucess."
		else
			echo "Not succesful."	
		fi
	fi
}

startup_fix()
{
	if [ -d /etc/psa ];then
		echo
		echo "${product_name} 3 can not be installed on a Plesk server."
		echo "Please install it on a different server!"
		echo "If you have any questions, contact 4PSA Help Desk at:"
		echo "https://help.4psa.com"
		echo
		exit 1	
	fi
}

welcome() {

curdepth=`pwd | wc -c`

if [ "${curdepth}" -lt 4 ];then
	die "Please do not execute this script from system /"
fi

if [ -f /usr/local/dnsmanager/.version ];then
	action='Upgrade'
	startup_fix
else
	action='Installation'
	startup_fix
fi


echo
echo	
echo	"${product_name} Command Line Auto-installer."
echo
echo	"Please read the Release Notes before running this script."
echo
echo	"Thank you for installing ${product_name}."
echo	"${action} procedure can start in a few moments."
echo
echo "Do you want to continue? [N] "

read answer

case "${answer}" in
	y*|Y*)
	;;
	*)
		echo
		echo "You will be able to install/update ${product_name} later."
		echo
		exit 1
	;;
esac
echo
}

check_os()
{
config="/etc/psa/psa.conf"
TARGET_OS="`uname -a`"
case "$TARGET_OS" in
	Linux*2.?.*?86*)
				
		if [ -f /etc/SuSE-release ];then
			sys="suse"
			release=`grep "^VERSION" /etc/SuSE-release | cut -d= -f2 | awk '{print $1}'`
		fi
   		if [ -f /etc/redhat-release ];then
			fedora=`grep "^Fedora" /etc/redhat-release`
			rhel=`grep "^Red Hat Enterprise Linux" /etc/redhat-release`
			centos=`grep "^CentOS" /etc/redhat-release`
	
			if [ ! -z "${fedora}" ];then
				sys="fc"
				release=`cat /etc/redhat-release | awk '{print $4}'`
			fi
			if [ ! -z "${rhel}" ];then
				sys="rhel"
				release=`cat /etc/redhat-release | awk '{print $7}' | cut -d'.' -f1`
			fi
			if [ ! -z "${centos}" ];then
				sys="centos"
				release=`cat /etc/redhat-release | awk '{i=NF-1; print $i}' | cut -d'.' -f1`
			fi
   		fi
   		if [ -z "${sys}" -o -z "${release}" ];then
   			echo "Can not determine Linux distribution."
   			exit 127
   		fi
   		
		;;
	*)	echo "You do not have a supported OS."
		exit 127
		;;
esac

if [ -z "${sys}" -o -z "${release}" ];then
	echo "You do not have a supported OS."
	exit 127
fi

if [ -f /proc/vz/veinfo ];then
# we are under Virtuozzo
	virtuozzo=1
else
	virtuozzo=0
fi
}

check_repo_cache()
{
get_yumconf
cache_dir=`grep "^cachedir" dnsmanager-yum.conf | cut -d'=' -f2`
    
if [ ! -d ${cache_dir} ];then
        mkdir -p ${cache_dir}
fi
}

import_gpg_keys()
{
# this is a hack
for gpgkey in `grep "^gpgkey" dnsmanager-yum.conf | cut -d'=' -f2 | awk '{print $1}'`;do
	rpm --import ${gpgkey} >/dev/null 2>&1
done
}

remove_dnsmanager()
{

if [ ! -f /usr/local/dnsmanager/.version ];then
	die "The product must be installed first, and then removed!"
fi

echo
echo
echo
echo	"ARE YOU SURE THAT YOU WANT TO UNINSTALL ${product_name}?"
echo 
echo	"You will loose EVERYTHING related to ${product_name}"
echo	"and you can recover later. If you are sure, type AGREE (in capitals)"
echo
echo "Do you want to continue? [N] "

read answer

case "${answer}" in
	AGREE)
		yum -y -c dnsmanager-yum.conf remove dnsmanager-admin-php dnsmanager-php dnsmanager-admin dnsmanager-core
		if [ $? -eq 0 ];then
			echo
			echo "An error occured might have occured while uninstalling ${product_name}."
			die "Please check the above log messages."
		else
			echo
			echo "${product_name} uninstalled succesfully."
			exit 0
		fi

	;;
	*)
		echo
		echo "Did you hear the voice? Wise choice."
		echo
		exit 0
	;;
esac
echo
}

check_update()
{
echo "==> Refreshing local repository with latest updates..."
yum -c dnsmanager-yum.conf check-update
}

get_variables()
{
        config="/etc/dnsmanager/dnsmanager.conf"
        if [ -f ${config} ];then
                DB_USER=`grep "^DB_USER\>" ${config} | awk '{print $2}'`
                DB_PASSWD=`grep "^DB_PASSWD\>" ${config} | awk '{print $2}'`
                DB_HOST=`grep "^DB_HOST\>" ${config} | awk '{print $2}'`
                DB_NAME=`grep "^DB_NAME\>" ${config} | awk '{print $2}'`
                DUMPS_D=`grep "^DUMPS_D\>" ${config} | awk '{print $2}'`
                MYSQL_SERVER=`rpm -q MySQL-server-standard | cut -d - -f 4 | awk -F'.' '{print $1$2}'`
        fi
}

product_upgrade()
{

        local rmpacklist="MySQL-server-standard perl-DBD-MySQL mysql5-python dnsmanager-admin python-mysql"
        NEWDNSMANAGER=`yum -c dnsmanager-yum.conf check-update | grep -w dnsmanager | grep -v "debug" | grep "^dnsmanager-core" | awk '{ print $(NF-1) }' | cut -d- -f1 | awk -F'.' '{print $1$2$3}'`
        if [ ! -z "${MYSQL_SERVER}" ];then
                if [ "${MYSQL_SERVER}" -lt 51 ] && [ -f ${config} ]; then
                        # have to check if the upgrade is for DNSMANAGER 3.6.0
                        if [ ! -z "${NEWDNSMANAGER}" ];then
                                if [ "${NEWDNSMANAGER}" -gt 350 ];then
                                echo -n "==> Making a database backup just to be safe ... "
                                current_date=`date +%k_%M_%S_%d_%m_%Y`
                                if [ ! -d ${DUMPS_D} ];then
                                        mkdir -p ${DUMPS_D}
                                fi
                                mysqldump --quote-names --extended-insert --routines --triggers -h${DB_HOST} -u${DB_USER} -p${DB_PASSWD} ${DB_NAME} > ${DUMPS_D}/dnsmanager${current_date}.sql
                                if [ $? -eq 0 ];then
                                        echo "OK"
                                else
                                        echo "Failed"
                                        die "Please make sure that you have a database backup before continuing the upgrade procedure"
                                fi
                                echo -n "==> Having to upgrade MySQL to 5.1 manually, please stand-by..."
                                        # mysql is old and we upgrade to DNSManager 3.6.0
                                        /etc/init.d/mysql stop
                                        killall -9 mysqld_safe mysqld 2>/dev/null
                                        sed '/default-storage_engine/d' /etc/my.cnf | sed '/skip-bdb/d' | sed '/skip-ndbcluster/d' > /etc/my.cnf$$
                                        mv /etc/my.cnf$$ /etc/my.cnf
                                        for remove_package in ${rmpacklist};do
                                                echo -n "..."
                                                rpm  -e ${remove_package} --nodeps 2>/dev/null
                                        done
                                fi
                        else
                                echo "Looks like ${product_name} is the latest version, we will check for additional components only!"
                        fi
                fi
        fi
}


install_with_yum()
{
echo
echo "==> Starting ${product_name} ${action} procedure."
echo "This process will take a while ..."
echo
yum -y -c dnsmanager-yum.conf groupupdate dnsmanager

if [ $? -eq 0 ];then
	echo
	echo "${product_name} ${action} completed succesfully!"
	exit 0
else
	echo
	echo "Could not install ${product_name}!"
	echo
	echo "If ${product_name} is conflicting with an installed package, uninstall the offending package with:"
	echo "rpm -e package_name"
	echo
	echo "Otherwise please contact support."
	exit 1
fi
}

check_selinux()
{
if [ -f /etc/sysconfig/selinux ];then
	echo 
	echo "==> Switching selinux to Permissive mode ..."
	sed '/SELINUX/s#enforcing#permissive#g' /etc/sysconfig/selinux > /etc/sysconfig/selinux.tmp
	cp -f /etc/sysconfig/selinux.tmp /etc/sysconfig/selinux && rm -f /etc/sysconfig/selinux.tmp
	/usr/sbin/setenforce 0
fi
}

# main

cd `dirname $0`
product_name='4PSA DNS Manager'
REPO='dnsmanager'
yum_path=''
wget_path=''
dsite='http://dnsmanager.4psa.com'

is_root

if [ "$1" = "remove" ];then
	remove_dnsmanager
else
	welcome
	check_os
	check_wget
	check_yum
	check_selinux
	import_4psa_key
	check_repo_cache
	import_gpg_keys
	remove_conflicts
	check_update
	get_variables
	product_upgrade
	install_with_yum
fi

exit 0

