#!/bin/sh

if [ "$1" = "-T" ]; then
	echo -n "(c) ISPsystem.com"
	exit 0
fi

Usage()
{
cat << EOU >&2
Usage:
	$0 --help		Prints this help
	$0 list [-i] [regex]	Lists packages and filters by regular expression if specified
				If -i specified, lists only installed packages, otherwise lists all available packages
	$0 show <package> [manager] [function]
					Shows package name and version if it is installed 
				and calls manager's 'manager' function 'function', if specified, with parameters:
				elid=<package> result=$exitcode
				exitcode = 0 means package is installed, otherwise the package is not installed
				or package manager returned an error code
	$0 content <package>	Lists files installed by package
	$0 contentmask <regex>	Lists files installed by packages, which names matches given regex
	$0 lastavail package	Show newer version of package if exists
	$0 rdepend package	Show packages which depends on given
EOU
}

List()
{
if [ -z "$package" ]; then
	package=.*
fi
if [ "$only_installed" = "true" ]; then
	/bin/rpm -qa --queryformat '%{NAME}\n'|grep -E -e "$package"
else
	yum -C -q list | awk -F '.' '{print $1}'|grep -E -v 'Installed|Available Packages'|grep -E -e "$package"
fi
exit $?
}

Show() {
	/bin/rpm -V --nodeps --nofiles --noscripts $package
	exitcode=$?
	if [ "$exitcode" -eq "0" ]; then
		/bin/rpm -q --queryformat '%{name}\t%{version}-%{release}\n' $package
	fi
	if [ -n "${mgr}" ] && [ -n "${func}" ]; then
		/usr/local/mgr5/sbin/mgrctl -m ${mgr} ${func} elid=$package result=$exitcode
	fi
	exit $exitcode
}

LastAvail()
{
yum -C -q list updates $package | awk -v mgr="$package" '$0 ~ mgr {print $2}'
exit $?
}

Content()
{
/bin/rpm -ql $package
exit $?
}

ContentMask()
{
for I in `/bin/rpm -qa --queryformat '%{NAME}\n'|grep -E -e "$package"`; do echo package:$I; /bin/rpm -ql $I; done
exit $?
}

RDepend() {
	local wr rq rdeps
	wr=$(rpm -q --whatrequires --qf "%{name}\n" "${package}" 2>/dev/null | awk '{if(!$2){print $0}}')
	rq=$(repoquery -q --qf "%{name}" --alldeps --installed --whatrequires "${package}" | grep -v "^${package}$")
	rdeps=$(echo "${wr}" "${rq}" | xargs -n1 | sort | uniq)
	echo "${rdeps}"
}

while true
do
	case "$1" in
		-h | --help)
			Usage
			exit 0
			;;
		list)
			if [ "$2" = "-i" ]; then
				only_installed="true"
				package=${3:-.}
			else
				only_installed="false"
				package=${2:-.}
			fi
			List
			exit 0
			;;
		show)
			package=${2:-.}
			Show
			mgr=${3}
			func=${4}
			exit 0
			;;
		content)
			package=${2:-.}
			Content
			exit 0
			;;
		contentmask)
			package=${2:-.}
			ContentMask
			exit 0
			;;
		lastavail)
			package=${2:-.}
			LastAvail
			exit 0
			;;
		rdepend)
			package=${2:-.}
			RDepend
			exit 0
			;;
		*)
			Usage
			exit 1
			;;
	esac
done
