#!/bin/bash

if [ "$1" = "-T" ]; then
	echo -n "(c) ISPsystem.com"
	exit 0
fi
cd "$(dirname $0)/../" || exit 1
PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
LD_LIBRARY_PATH=""
MGRDIR=/usr/local/mgr5
cd ${MGRDIR} || exit 1
. ${MGRDIR}/lib/pkgsh/core_pkg_funcs.sh || exit 1

# PREINST_HOOKS needs for repository add
UPGRADE_HOOKS=""
CORE_UPGRADE_PKGS=""
if [ -d ${MGRDIR}/lib/pkgsh/hooks/upgrade ]; then
	for hook_file in $(find ${MGRDIR}/lib/pkgsh/hooks/upgrade/ -type f); do
		# shellcheck source=/dev/null
		. "${hook_file}"
	done
fi

if [ "$SSH_CONNECTION" = "" ]; then
	exec 1>>var/pkg.log
	echo
	echo -n "*** "
	date
	if [ "$1" = "" ]; then
		echo "*** UPGRADING PACKAGES"
	else
		echo "*** UPGRADING PACKAGE $1"
	fi
fi

clean_unused_repo_yum() {
	local isp_repos
	isp_repos=$(yum -C repolist | awk '$1 ~ /ispsystem/ {print $1}' | awk -F/ '{print $1}')
	for crepo_path in $(find /var/cache/yum/*/*/  -maxdepth 1 -mindepth 1 -type d -name "ispsystem-*" -print | sort); do
		crepo_needing="false"
		crepo=${crepo_path##*/}
		for irepo in ${isp_repos}; do
			if [ "x${irepo}" = "x${crepo}" ]; then
				echo "Repo ${crepo} used"
				crepo_needing="true"
				break
			fi
		done
		if [ "x${crepo_needing}" = "xfalse" ]; then
			if echo "${crepo_path}" | grep -q "^/var/cache/yum"; then
				echo "Repo ${crepo} not used. Removing it"
				rm -rf "${crepo_path}"
			fi
		fi
	done
}

clean_unused_repo_dnf() {
	local isp_repos
	isp_repos=$(dnf -C repolist | awk '$1 ~ /ispsystem/ {print $1}' | awk -F/ '{print $1}')
	for crepo_path in $(find /var/cache/dnf/  -maxdepth 1 -mindepth 1 -type d -name "ispsystem-*" -print | sort); do
		crepo_needing="false"
		crepo=${crepo_path##*/}
		crepo=${crepo%-*}
		for irepo in ${isp_repos}; do
			if [ "x${irepo}" = "x${crepo}" ]; then
				echo "Repo ${crepo} used"
				crepo_needing="true"
				break
			fi
		done
		if [ "x${crepo_needing}" = "xfalse" ]; then
			if echo "${crepo_path}" | grep -q "^/var/cache/dnf"; then
				echo "Repo ${crepo} not used. Removing it"
				rm -rf "${crepo_path}"
			fi
		fi
	done


}

clean_unused_repo() {
	if [ ${OSVERSION} -ge 8 ]; then
		clean_unused_repo_dnf
	else
		clean_unused_repo_yum
	fi

}

for f in ispsystem ispsystem-base ; do
	fname=/etc/yum.repos.d/${f}.repo
	if [ -f ${fname} ]; then
		#if ! grep -q '^###' ${fname} && grep -q cdn.ispsystem.com ${fname} ; then
		#	echo "*** Replacing mirror url"
		#	sed -i -r 's|http://cdn.ispsystem.com|http://download.ispsystem.com|' ${fname} || :
		#el
		if grep -q /mirrorlist-install.txt ${fname} ; then
			sed -i -r "s|(mirrorlist=http://download.ispsystem.com/repo/centos/\w+)/mirrorlist-install.txt|\1/mirrorlist.txt|" ${fname} || :
		fi

		# Download GPG key
		if [ ! -s /etc/pki/rpm-gpg/RPM-GPG-KEY-ISPsystem ]; then
			wget -O /etc/pki/rpm-gpg/RPM-GPG-KEY-ISPsystem "http://download.ispsystem.com/repo/ispsystem.gpg.key" || :
		fi
		# Download GPG key if can not access to download (use cdn)
		if [ ! -s /etc/pki/rpm-gpg/RPM-GPG-KEY-ISPsystem ]; then
			wget -O /etc/pki/rpm-gpg/RPM-GPG-KEY-ISPsystem "http://cdn.ispsystem.com/repo/ispsystem.gpg.key" || :
		fi

		# Enable gpgkey verification
		if grep -q 'gpgkey=$' ${fname} ; then
			sed -i -r "s/(gpgkey=)$/\1file:\/\/\/etc\/pki\/rpm-gpg\/RPM-GPG-KEY-ISPsystem/g" ${fname}
			sed -i -r "s/gpgcheck=0/gpgcheck=1/g" ${fname}
		fi

	fi
done

check_df_all() {
	if ! CheckDF / 300 ; then echo "Too low disk space in /" ; return 1 ; fi
	if ! CheckDF /usr/local/mgr5 300 ; then echo "Too low disk space in /usr/local/mgr5" ; return 1 ; fi
}

yum clean all

# Update yum first. Fix #CORE-85
if ! yum --help 2>/dev/null| grep -q downloadonly ; then
	yum -y update yum 2>&1 || :
fi
if [ "$1" = "coremanager" ]; then
        if [ ${OSVERSION} -ge 8 ]; then
               PKGS=$(rpm -q --whatrequires --queryformat '%{NAME} ' "${1}")
        else
               PKGS=$(rpm -q --whatrequires "${1}" | xargs)
        fi
	PKGS="${PKGS} ${CORE_UPGRADE_PKGS}"
	/usr/bin/yum -y --downloadonly update ${1} ${PKGS} 2>&1 && check_df_all && /usr/bin/yum -y update ${1} ${PKGS} 2>&1
else
	/usr/bin/yum -y --downloadonly update $1 2>&1 && check_df_all && /usr/bin/yum -y update ${1} 2>&1
fi
exitcode=$?
if [ -n "$2" ] && [ -n "$3" ]; then
	sbin/mgrctl -m "$2" "$3" elid="$1" result="$exitcode"
fi
if [ ${exitcode} -eq 0 ]; then
	clean_unused_repo || :
fi
exit $exitcode
