#!/bin/sh
# vim: ts=4 noexpandtab

MGRDIR=/usr/local/mgr5
. ${MGRDIR}/lib/pkgsh/core_pkg_funcs.sh

# Определяем ispmanager-lite тут или ispmanager-node
if IsMgrExist ispmgrnode ; then
	ISPMGR=ispmgrnode
else
	ISPMGR=ispmgr
fi

MGRDIR="/usr/local/mgr5"
ISPMGRCTL="/usr/local/mgr5/sbin/mgrctl -m ${ISPMGR}"

AddWebmail() {
	if [ "#${1}" = "#" ]; then
		echo "Empty argument"
		return 1
	fi
	WEBMAILS=$(${ISPMGRCTL} paramlist elid=WebMail) || :
	WEBMAILS=${WEBMAILS##*=}
	if ! echo ${WEBMAILS} | grep -q "${1}"; then
		if [ "${WEBMAILS}#" = "#" ]; then
			WEBMAILS="${1}"
		else
			WEBMAILS="${WEBMAILS} ${1}"
		fi
		${ISPMGRCTL} paramlist.edit elid=WebMail value="${WEBMAILS}" sok=ok
		ReloadMgr ${ISPMGR}
		return 0
	fi
}

RemoveWebmail() {
	if [ "#${1}" = "#" ]; then
		echo "Empty argument"
		return 1
	fi
	WEBMAILS=$(${ISPMGRCTL} paramlist elid=WebMail) || :
	WEBMAILS=${WEBMAILS##*=}
	if echo ${WEBMAILS} | grep -q "${1}"; then
		WEBMAILS=$(echo "${WEBMAILS}" | sed -r "s|\s*${1}\s*||")
		${ISPMGRCTL} paramlist.edit elid=WebMail value="${WEBMAILS}" sok=ok
		return 0
	fi
}

AddWebModule() {
	if [ "#${1}" = "#" ]; then
		echo "Empty argument"
		return 1
	fi
	WEBM=$(${ISPMGRCTL} paramlist elid=WebModules) || :
	WMLIST=${WEBM##*=}
	if ! echo ${WMLIST} | grep -q "${1}"; then
		if [ "${WMLIST}#" = "#" ]; then
			WMLIST="${1}"
		else
			WMLIST="${WMLIST} ${1}"
			if [ "${WEBRECONFIGURE_DISABLE}" != "yes" ]; then
				${ISPMGRCTL} webreconfigure.initialize shutdown=on || return 1
			fi
		fi
		${ISPMGRCTL} paramlist.edit elid=WebModules value="${WMLIST}" sok=ok
		if [ "${WEBRECONFIGURE_DISABLE}" != "yes" ]; then
			${ISPMGRCTL} -R webreconfigure.restore || :
		fi
		return 0
	fi
}

RemoveWebModule() {
	if [ "#${1}" = "#" ]; then
		echo "Empty argument"
		return 1
	fi
	WEBM=$(${ISPMGRCTL} paramlist elid=WebModules) || :
	WMLIST=${WEBM##*=}
	if echo ${WMLIST} | grep -q "${1}"; then
		WMLIST=$(echo "${WMLIST}" | sed -r "s|\s*${1}\s*||")
		if [ "${WEBRECONFIGURE_DISABLE}" != "yes" ]; then
			${ISPMGRCTL} webreconfigure.initialize shutdown=on || return 1
		fi
		${ISPMGRCTL} paramlist.edit elid=WebModules value="${WMLIST}" sok=ok
		if [ ! "${WMLIST}#" = "#" ] && [ "${WEBRECONFIGURE_DISABLE}" != "yes" ]; then
			${ISPMGRCTL} -R webreconfigure.restore || :
		fi
		return 0
	fi
}

ReloadWeb() {
	if [ ${OSTYPE} = "REDHAT" ]; then
		ANAME=httpd
		NNAME=nginx
	elif [ ${OSTYPE} = "DEBIAN" ]; then
		ANAME=apache2
		NNAME=nginx
	elif [ ${OSTYPE} = "FREEBSD" ]; then
		ANAME=apache24
		NNAME=nginx
	else
		echo "Can not detect Apache script"
		exit 1
	fi
	WEBM=$(${ISPMGRCTL} paramlist elid=WebModules) || :
	WMLIST=${WEBM##*=}
	if echo ${WMLIST} | grep -q "apache"; then
		ReloadService ${ANAME} soft
	fi
	if echo ${WMLIST} | grep -q "nginx"; then
		ReloadService ${NNAME} soft
		# php-fpm also restart
		if [ -f /etc/init.d/php-fpm ]; then
			ReloadService php-fpm soft
		elif [ -f /usr/local/etc/rc.d/php-fpm ]; then
			ReloadService php-fpm soft
		elif [ -f /usr/bin/systemctl ] && systemctl list-units 2>/dev/null| grep -q php-fpm ; then
			# Centos7 and other systemd
			ReloadService php-fpm
		fi
	fi


}

CheckDisabledPage() {
	if [ -f "${MGRDIR}/etc/templates/disabled.html" ]; then
		if [ ! -f "${MGRDIR}/www/disabled/index.html" ]; then
			mkdir -p ${MGRDIR}/www/disabled
			chmod 755 ${MGRDIR}/www/disabled
			cp ${MGRDIR}/etc/templates/disabled.html ${MGRDIR}/www/disabled/index.html
			chmod 644 ${MGRDIR}/www/disabled/index.html
		fi
	fi
}

PostconfSet() {
	postconf -e $1="$2"
}

PostconfSetDef() {
	postconf -e $1="$(postconf -d $1 | awk -F= '{print $2}')"
}

PostconfAdd() {
	CURVAL="$(postconf ${1} | awk -F= '{print $2}')"
	if ! echo "${CURVAL}" | grep -q "${2}" ; then
		if [ ! -n "${CURVAL}" ]; then
			VAL="${2}"
		else
			VAL="${CURVAL}, ${2}"
		fi
		PostconfSet ${1} "${CURVAL}, ${2}"
	fi
}

PostconfRemove() {
	CURVAL="$(postconf ${1} | awk -F= '{print $2}')"
	if echo ${CURVAL} | grep -q "${2}" ; then
		VAL=$(echo "${CURVAL}" | sed "s|${2}||")
		VAL=$(echo "${VAL}" | sed -r "s|,\s*$||; s|(,\s*)+|, |g; s|^\s*,\s*||")
		PostconfSet ${1} "${VAL}"
	fi
}

ServiceAddmon() {
	if [ "#${1}" = "#" ]; then
		echo "Empty argument"
		return 1
	fi
	${ISPMGRCTL} services.addmon name="${1}" sok=ok >/dev/null 2>&1 ||:
}

ServiceDeletemon() {
	if [ "#${1}" = "#" ]; then
		echo "Empty argument"
		return 1
	fi
	${ISPMGRCTL} services.deletemon name="${1}" sok=ok >/dev/null 2>&1 ||:
}

DisableServiceIspmgr() {
	if [ "#${1}" = "#" ]; then
		echo "Empty argument"
		return 1
	fi
	ServiceDeletemon ${1}
	DisableService ${1}
}

CheckConfigPkg() {
	# $1 - целевой конфиг.
	# $2 - исходный. Если не указан, то совпадает с целевым
	#
	# Если существует файл, то его помувать
	T=$1
	if [ -z "${2}" ]; then
		S=$1
	else
		S=$2
	fi
	if [ -f ${MGRDIR}/etc/${ISPMGR}.conf.d/${T}.conf ]; then
		if [ ! -L ${MGRDIR}/etc/${ISPMGR}.conf.d/${T}.conf ]; then
			rm -f ${MGRDIR}/etc/conf.d/${S}.conf
			mv ${MGRDIR}/etc/${ISPMGR}.conf.d/${T}.conf ${MGRDIR}/etc/conf.d/${S}.conf
		fi
	fi
}

MakeConfigLink() {
	# $1 - целевой конфиг.
	# $2 - исходный. Если не указан, то совпадает с целевым
	T=$1
	if [ -z "${2}" ]; then
		S=$1
	else
		S=$2
	fi
	mkdir -p ${MGRDIR}/etc/${ISPMGR}.conf.d
	test -L ${MGRDIR}/etc/${ISPMGR}.conf.d/${T}.conf || ln -sf ../conf.d/${S}.conf ${MGRDIR}/etc/${ISPMGR}.conf.d/${T}.conf
	return $?
}

RemoveConfigLink() {
	# $1 - имя конфига
	rm -f ${MGRDIR}/etc/${ISPMGR}.conf.d/${1}.conf
}

CreateCert() {
	# $1 - key
	# $2 - cert
	# $3 - lenght(default 1024)
	local len keydir crtdir
	if [ -n "${3}" ]; then
		len=${3}
	else
		len=1024
	fi
	test -z "$1" && return 1
	test -z "$2" && return 1
	keydir=$(dirname ${1})
	crtdir=$(dirname ${2})
	test -d "${keydir}" || mkdir -p "${keydir}"
	test -d "${crtdir}" || mkdir -p "${crtdir}"

	openssl req -newkey "rsa:${len}" -nodes -keyout ${1} -out ${2} -x509 -days 3650 -subj "/C=XX/ST=XX/L=XX/O=XX/OU=XX/CN=example.com/emailAddress="root@$(hostname)
	chmod 400 "${1}"
}

CreateMailer() {
	# $1 - bin
	# $2 - mq
	# $3 - alias
	cat > /etc/mail/mailer.conf << EOF
sendmail        $1
send-mail       $1
mailq           $1 $2
newaliases      $1 $3
hoststat        $1
purgestat       $1
EOF
}

DisableFirewalld() {
	ISPMGRCONF=${MGRDIR}/etc/${ISPMGR}.conf
	grep "path rh-iptables-save" ${ISPMGRCONF} || echo "path rh-iptables-save /usr/libexec/iptables/iptables.init save" >> ${ISPMGRCONF}
	grep "path rh-ip6tables-save" ${ISPMGRCONF} || echo "path rh-ip6tables-save /usr/libexec/iptables/ip6tables.init save" >> ${ISPMGRCONF}

	systemctl stop firewalld
	systemctl disable firewalld

	systemctl enable iptables
	systemctl enable ip6tables
	systemctl start iptables
	systemctl start ip6tables
}


AddPath() {
	path=${1}
	value="${2}"
	name=${3}
	test -d ${MGRDIR}/etc/${ISPMGR}.conf.d || mkdir -p ${MGRDIR}/etc/${ISPMGR}.conf.d
	conf=${MGRDIR}/etc/${ISPMGR}.conf.d/${name}.conf
	if [ ! -e ${conf} ] && [ -e ${MGRDIR}/etc/conf.d/${name}.conf ]; then
		conf=${MGRDIR}/etc/conf.d/${name}.conf
	fi
	test -e ${conf} || touch ${conf}
	if ! grep -qE "^path\s${path}\s" ${conf} ; then
		echo "path ${path} ${value}" >> ${conf}
	fi
}

UpdatePath() {
	path=${1}
	value="${2}"
	name=${3}
	test -d ${MGRDIR}/etc/${ISPMGR}.conf.d || mkdir -p ${MGRDIR}/etc/${ISPMGR}.conf.d
	conf=${MGRDIR}/etc/${ISPMGR}.conf.d/${name}.conf
	if [ ! -e ${conf} ] && [ -e ${MGRDIR}/etc/conf.d/${name}.conf ]; then
		conf=${MGRDIR}/etc/conf.d/${name}.conf
	fi
	test -e ${conf} || touch ${conf}
	if ! grep -qE "^path\s${path}\s" ${conf} ; then
		echo "path ${path} ${value}" >> ${conf}
	else
		sed --follow-symlinks -i -r "s|(path\s+${path})\s+.+|\1 ${value}|" ${conf}
	fi
}

version_ge() {
	test "$(echo "$@" | tr " " "\n" | sort -V | tail -n 1)" = "$1";
}

version_gt() {
	test "$1" = "$2" && return 1
	version_ge "$1" "$2"
}
