#!/bin/bash

CENTOS_RELEASE_FILE="/etc/redhat-release"
COREMGR_NAME="coremanager"
LOG_FILE="/usr/local/mgr5/var/pkgcheck.log"
TMP_FILE="/usr/local/mgr5/var/pkgcheck.tmp"
PKG_CHECK="/usr/local/mgr5/etc/scripts/pkgcheck.sh"
PKG_UPGRADE="/usr/local/mgr5/sbin/pkgupgrade.sh"
YUM_PID_FILE="/var/run/yum.pid"
LT_WRAPPER="/usr/local/mgr5/sbin/lt_wrapper"
ATTEMPTS_COUNT=3
TIMEOUT="1 hour"

log () {
      echo "$(date): $1"
}

{
check_yum () {
	log "Check that yum is not running"
	if [ -f "${YUM_PID_FILE}" ] && ps -p $(cat $YUM_PID_FILE); then
		log "yum is running - try later"
		attempt=0
		if [ -f "${TMP_FILE}" ]; then
			attempt=$(cat "${TMP_FILE}")
		fi
		attempt=$((attempt + 1))
		log "attempt ${attempt} of ${ATTEMPTS_COUNT}"
		if [ "${attempt}" -lt "${ATTEMPTS_COUNT}" ]; then
			echo "${attempt}" > "${TMP_FILE}"
			echo "${PKG_CHECK}" | at -m now +"${TIMEOUT}"
			exit
		else
			log "searching duplicated packages was failed"
			exit 1
		fi
	fi
	echo quit | yum shell
	log "yum not running - ok"
	rm -f "${TMP_FILE}"
}

log "Start searching duplicated packages"

#if OS - centos
if [ -f "${CENTOS_RELEASE_FILE}" ]; then
	log "OS - Centos"
	check_yum
	log "Check coremanager count"
	if [ "$(rpm -q --qf '%{NAME}\n' "${COREMGR_NAME}" | wc -l)" -gt 1 ]; then
		log "coremanager count more than one"
		dupes_packages=$(rpm -q --qf='%{NAME}\n' --whatrequires "${COREMGR_NAME}" | sort | uniq -d; echo "${COREMGR_NAME}")
		#loop in duped packages
		log "Packages: [ ${dupes_packages} ] are duplicated"
		for package in ${dupes_packages}; do
			#get full names of duped packages
			packs=$(rpm -q "${package}")
			log "process ${pack1} and ${pack2}"
			#pack1 - first duped, pack2 - second
			pack1=$(echo "${packs}" | head -n 1)
			pack2=$(echo "${packs}" | tail -n 1)
			#get build numbers of duped packages
			pack1build=$(rpm -q --qf '%{RELEASE}\n' "${package}" | head -n 1 | cut -f 1 --delimiter=".")
			pack2build=$(rpm -q --qf '%{RELEASE}\n' "${package}" | tail -n 1 | cut -f 1 --delimiter=".")

			#remove newest package without dependencies
			if [ "${pack1build}" -gt "${pack2build}" ]; then
				rpm -e --nodeps "${pack1}"
				log "${pack1} deleted"
			else
				rpm -e --nodeps "${pack2}"
				log "${pack2} deleted"
			fi
		done
		#try to update once
		log "starting upgrade ${coremgr_name}"
		sh "${PKG_UPGRADE}" "${COREMGR_NAME}"
		log "Run lt_wrapper"
		"${LT_WRAPPER}"
	fi
	log "coremanager only one, just ok. Exit"
fi
} &> "${LOG_FILE}"
