#!/bin/sh

# Copyright (c) 2002-2018 by 4PSA, Inc
# All rights reserved

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

# Download site
dsite='http://download2.4psa.com/dnsmanager/latest'

# Version file
vfile='/usr/local/dnsmanager/.version'


cleanup()
{
    rm -f ${repolocal} local$$
    rm -f /var/lock/subsys/dnsinstaller
    exit 1
}

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
            cleanup
        ;;
    esac
}

die()
{
    echo
    echo "ERROR: $*"
    echo
    echo "Check the error reason, fix and try again."
    echo "You can welcome to open a support ticket at http://help.4psa.com!"
    echo
    cleanup
}

ok()
{
	echo "OK!"
	echo
}

import_4psa_key()
{
    local imported_keys=`rpm -qi gpg-pubkey-* | grep "Rack-Soft, Inc" | wc -l`

    if [ "${imported_keys}" -eq 0 ];then
        echo -n "Importing 4PSA RPM key... "
        rm -f 4PSA-GPG-KEY
        curl -L http://www.4psa.com/software/4PSA-GPG-KEY -o 4PSA-GPG-KEY 2> /dev/null
        rpm --import 4PSA-GPG-KEY
        if [ $? -eq 0 ];then
            ok
        else
            die "Could not import 4PSA signature. RPM package cannot be checked without it!"
        fi
    fi
}


check_deps()
{
    which yum >/dev/null 2>&1
    if [ $? -gt 0 ];then
        echo "yum binary can not be found."
        die "It's not in the system PATH or in a standard location."
    fi
	
    which ifconfig >/dev/null 2>&1
    if [ $? -gt 0 ];then
        yum -y install net-tools >/dev/null 2>&1
        if [ $? -gt 0 ];then	
            echo "ifconfig binary can not be found and package net-tools could not be installed."
            die "It's not in the system PATH or in a standard location."
        fi
    fi
}


remove_conflicts()
{
    if [ ! -d /usr/local/dnsmanager ];then
        echo
        echo "==> Trying to remove unwanted packages that conflict with ${product_name} ..."
        yum ${step} -c ${yumconf} remove httpd >/dev/null 2>&1
		ok
    fi

    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
       
        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
            ok
        else
            echo "Not successful."
        fi
        showfinalnotice=1
    else
        showfinalnotice=0
    fi
	
    if [ ${release} -eq 6 ];then
        esmtpver=`rpm -qi libesmtp | grep "^Version" | cut -d: -f2 | sed 's/\.//g' | awk '{print $1}'`
        if [[ "${esmtpver}" -gt 104 ]];then
            rpm -e libesmtp --nodeps 2> /dev/null
        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
        cleanup
    fi
}

welcome() {

    curdepth=`pwd | wc -c`

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

    echo
    echo
    echo    "${product_name} Command Line Auto-installer."
    echo
    echo    "Please read the Release Notes before running this installer."
    echo
    echo    "Thank you for installing ${product_name}."
    echo    "${action1} 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
            cleanup
        ;;
    esac
    echo
}

check_os()
{
    if [ -f /etc/redhat-release ];then
        rhel=`grep "^Red Hat Enterprise Linux" /etc/redhat-release`
        centos=`grep "^CentOS" /etc/redhat-release`
        if [ ! -z "${rhel}" ];then
            sys="rhel"
            release=`cat /etc/redhat-release | awk '{print $7}' | cut -d'.' -f1`
        fi
        if [ ! -z "${centos}" ];then
            sys="rhel"
            release=`cat /etc/redhat-release | awk '{i=NF-1; print $i}' | cut -d'.' -f1`
        fi
        if [ -z "${sys}" -o -z "${release}" ];then
            echo "Can not determine Linux distribution."
            exit 127
        fi
    fi
    
    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
    
    if [ "${DNSDEBUG}" ];then
        debugrpm='--rpmverbosity=debug'
    else
        debugrpm=''
    fi
}

check_av_updates()
{
    if [ -f ${vfile} ]; then
        no_updates=`yum -c ${yumconf} --disablerepo=base --disablerepo=updates check-update | egrep "${grepdnsmanagerrepo}" | grep -v "\-devel" | grep -v "\-debuginfo" | wc -l`
        if [ -z "${no_updates}" ];then
            no_updates=0
        fi
    fi
}

determine_op()
{
    if [ -f ${vfile} ];then
        action="There are ${no_updates} packages for upgrade. Procedure can start immediatly."
        action1="upgrade"
    else
        action='Installation procedure can start immediatly.'
        action1="installation"
    fi
}

get_yumconf()
{
    local repo=''
    curl --connect-timeout 20 -L ${origin} -o ${repolocal} >/dev/null 2>&1
    if [ ! -f ${repolocal} ];then
        die "Could not download from origin: ${origin}"
    fi

    local newsign=`md5sum ${repolocal} | awk '{print $1}' 2>/dev/null`

    if [ -f ${yumconf} ];then
        local oldsign=`grep "^#sign=" ${yumconf} | cut -d"=" -f2`
    fi

    if [ ! -z ${oldsign} ];then
        if [ "${oldsign}" = "${newsign}" ];then

            local localrepos=`grep "^\[" ${yumconf} | grep -v "\[main\]" | cut -d "[" -f 2 | cut -d "]" -f1 | grep -vw "base" | grep -vw "updates"`

            for localrepo in ${localrepos};do
                disablednsmanager="${disablednsmanager} --disablerepo=${localrepo}"
            done
            return 0
        fi
    fi

    local alldeps=`grep "^http" ${repolocal}`

    if [ -z "${alldeps}" ];then
        die "Repository file downloaded from ${origin} is invalid!"
    fi

    if [ -f ${yumconf} ];then
        mv -f ${yumconf} ${yumconf}.old
    fi

    echo "[main]" > ${yumconf}
    echo "cachedir=/var/cache/dnsmanager" >> ${yumconf}
    echo "keepcache=0" >> ${yumconf}
    echo "debuglevel=2" >> ${yumconf}
    echo "logfile=/var/log/dnsmanager-update.log" >> ${yumconf}
    echo "diskspacecheck=1" >> ${yumconf}
    echo "exactarch=1" >> ${yumconf}
    echo "obsoletes=1" >> ${yumconf}
    echo "metadata_expire=300" >> ${yumconf}
    echo "installonly_limit=3" >> ${yumconf}
    echo "reposdir=./" >> ${yumconf}
    echo "exclude=hwphp, hwgdb" >> ${yumconf}
    echo "plugins=1" >> ${yumconf}

    # This is for redhat
    if [ ! -z "${rhel}" ];then
        echo "include=/etc/yum.repos.d/redhat.repo" >> ${yumconf}
    fi
    echo >> ${yumconf}
    
    for repo in ${alldeps};do
        curl --connect-timeout 20 -L ${repo} -o local$$ >/dev/null 2>&1
        if [ $? -eq 0 -a -f local$$ ];then
            local localrepo=`grep "^\[" local$$ | cut -d "[" -f 2 | cut -d "]" -f1`
            dnsmanagerrepo="${dnsmanagerrepo} ${localrepo}"
            if [ -z "${grepdnsmanagerrepo}" ];then
                grepdnsmanagerrepo="${localrepo}"
            else
                grepdnsmanagerrepo="${grepdnsmanagerrepo} \| ${localrepo}"
            fi

            disablednsmanager="${disablednsmanager} --disablerepo=${localrepo}"

            cat local$$ >> ${yumconf}
            echo >> ${yumconf}
            rm -f local$$
        else
            die "Could not download from origin repo: ${repo}"
        fi
    done

    # Add OS repositories
    # This is for centos
    if [ ! -z "${centos}" ];then

        echo "[base]" >> ${yumconf}
        echo "name=CentOS-\$releasever - Base" >> ${yumconf}
        echo "mirrorlist=http://mirrorlist.centos.org/?release=\$releasever&arch=\$basearch&repo=os" >> ${yumconf}
        echo "#baseurl=http://mirror.centos.org/centos/\$releasever/os/\$basearch/" >> ${yumconf}
        echo "gpgcheck=1" >> ${yumconf}
        echo "gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-${release}" >> ${yumconf}
        echo >> ${yumconf}

        echo "[updates]" >> ${yumconf}
        echo "name=CentOS-\$releasever - Updates" >> ${yumconf}
        echo "mirrorlist=http://mirrorlist.centos.org/?release=\$releasever&arch=\$basearch&repo=updates" >> ${yumconf}
        echo "#baseurl=http://mirror.centos.org/centos/\$releasever/updates/\$basearch/" >> ${yumconf}
        echo "gpgcheck=1" >> ${yumconf}
        echo "gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-${release}" >> ${yumconf}
        echo >> ${yumconf}
    fi
    echo "#sign=${newsign}" >> ${yumconf}
    return 0
}


import_gpg_keys()
{
    # this is a hack
    for gpgkey in `grep "^gpgkey" ${yumconf} | 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 ${step} -c ${yumconf} remove httpsa-admin-php dnsmanager-webmanagement httpsa-admin dnsmanager-core dnsmanager-corebin dnsmanager-sync
            if [ $? -eq 0 ];then
                echo
                echo "An error might have occurred while uninstalling ${product_name}."
                die "Please check the above log messages."
            else
                echo
                echo "${product_name} uninstalled successfully."
                exit 0
            fi
        ;;
        *)
            echo
            echo "Did you hear the voice? Wise choice."
            echo
            exit 0
        ;;
    esac
    echo
}

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}'`
    fi
}

update_os()
{
    echo "==> Updating Operating System packages (other than ${product_name})..."
    yum ${step} -c ${yumconf} update ${disablednsmanager}
    if [ $? -gt 0 ];then
        die "Could not upgrade Operating System!"
    fi
    echo
}

product_upgrade()
{
    local rmpacklist="MariaDB-server perl-DBD-MariaDB mysql55-python dnsmanager-admin python-mysql"
    NEWDNSMANAGER=`yum -c ${yumconf} check-update | grep -w dnsmanager | grep -v "debug" | grep "^dnsmanager-core" | awk '{ print $(NF-1) }' | cut -d- -f1 | awk -F'.' '{print $1$2$3}'`
}


install_with_yum()
{
    echo
    echo "==> Starting ${product_name} ${action1} procedure."
    echo "This process will take a while ..."
    echo
    yum ${step} -c ${yumconf} clean metadata ${output}
    echo

    if [ "${action1}" = "upgrade" ];then

        if [ -f /etc/dnsmanager/dnsmanager.conf ];then
            local DB_HOST=`grep "^DB_HOST" /etc/dnsmanager/dnsmanager.conf | awk '{print $2}'`
            local DB_USER=`grep "^DB_USER" /etc/dnsmanager/dnsmanager.conf | awk '{print $2}'`
            local DB_PASSWD=`grep "^DB_PASSWD" /etc/dnsmanager/dnsmanager.conf | awk '{print $2}'`
        fi
	
        if [ "${DB_HOST}" -a "${DB_PASSWD}" -a "${DB_USER}" ];then
            mysql -h${DB_HOST} -u${DB_USER} -p${DB_PASSWD} -e"SHOW VARIABLES LIKE '%version%';" | grep -i "10." | grep -i "mariadb" >/dev/null 2>&1
            if [ $? -gt 0 ];then
                my_upgrade=1
            fi
        fi
	
        yum ${debugrpm} ${step} -c ${yumconf} update MariaDB-server MariaDB-client MariaDB-shared
		
        if [ $? -gt 0 ];then
            die "Could not complete MySQL and dependencies upgrade!"
        else
            if [ ${my_upgrade} -eq 1 ];then
                mysql_upgrade -h${DB_HOST} -u${DB_USER} -p${DB_PASSWD} >/dev/null 2>&1
                service mysql restart
            fi
        fi
		
        yum ${debugrpm} ${step} -c ${yumconf} upgrade
    else
        yum ${debugrpm} ${step} -c ${yumconf} clean metadata ${output}
        yum ${debugrpm} ${step} -c ${yumconf} install dnsmanager-webmanagement
    fi
	
	if [ $? -eq 0 ];then
		if [ ${showfinalnotice} -eq 1 ];then
			local localip=`/sbin/ifconfig | grep -v "127.0.0.1" | grep -v "inet6" | grep -i "inet" | head -1 | awk '/inet/{print $2}' | cut -d: -f2 | awk '{print $1}'`
			echo
			echo "------IMPORTANT---------"
			echo
			echo "Point your browser to DNS Manager Web Interface at https://${localip}"
			echo
			echo "Username: admin"
			echo "Password: welcome"
			echo
			echo "Please LOGIN immediately and CHANGE the password."
			echo
			echo "------IMPORTANT---------"
			
            /sbin/chkconfig --add mysql 2>/dev/null || :
        else
            echo
            echo "${product_name} ${action1} completed successfully!"
        fi
    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."
        cleanup
    fi
}

check_selinux()
{
    if [ -f /etc/sysconfig/selinux ];then
        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
}

check_lockfile()
{
    which lockfile >/dev/null 2>&1
    if [ $? -gt 0 ];then
        # let's install lockfile
        echo "==> Installing required packages..."
        yum -y install procmail >/dev/null 2>&1
        if [ $? -gt 0 ];then
            die "Could not install all pre-required packages!"
        fi
    fi
}

origin_find()
{
	# Determine installer course
	if [ ! -z "${DNSMANAGER_REPO}" ];then
        origin=${DNSMANAGER_REPO}/${sys}${release}/repo.dep
		dsite=${DNSMANAGER_REPO}
	else
		origin=${dsite}/${sys}${release}/repo.dep
	fi
}

# main

cd `dirname $0`
product_name='4PSA DNS Manager'
repolocal=repo.dep$$
yumconf="/etc/dnsmanager-yum.conf"
dnsmanagerrepo=''
grepdnsmanagerrepo=''
disablednsmanager=''
lockfile='/var/lock/subsys/dnsinstaller'
step='-y'
output=>/dev/null 2>&1

is_root
auto=0
check=0
my_upgrade=0

# This is automode
if [ "$1" = "auto" ];then
    auto=1
fi

# This is check
if [ "$1" = "check" ];then
    check=1
fi

# This is removal
if [ "$1" = "remove" ] || [ "$2" = "remove" ];then
    remove_dnsmanager
    exit 0
fi


check_os
origin_find
check_deps
get_yumconf
check_av_updates
if [ "${check}" = "1" ];then
    exit ${no_updates}
fi
determine_op

if [ "${auto}" = "0" ];then
    welcome
fi

check_lockfile
check_selinux

lockfile -r 10 ${lockfile}
import_4psa_key
import_gpg_keys
remove_conflicts
update_os
get_variables
product_upgrade
install_with_yum
rm -f ${lockfile}
rm -f ${repolocal} local$$
exit 0
