#!/bin/sh -efu

: ${rpm_arch?} ${rpm_name?} ${rpm_filenames?} ${rpm_perms_filenames?} ${rpm_sourcerpm?}

check_python()
{
	# Check python for binary rpms only.
	[ "$package_type" = bin ] || return 0

	# python base packages are exception.
	if printf %s "$rpm_sourcerpm" |
	   egrep -qx 'python([2-9](\.[0-9])?)?-[^-]+-[^-]+'; then
		return 0
	fi

	local f="$1" && shift || return 1
	local rc=0

	if printf %s "$rpm_filenames" 2>/dev/null |
	   egrep '^/usr/lib(64)?/python[23][.][0-9]/' 2>/dev/null |
	   egrep -vqs '^/usr/lib(64)?/python[23][.][0-9]/(lib-dynload|site-packages|tools)/'; then
		FileError 'python files inside %python_libdir can be placed only in %python_sitelibdir, %python_tooldir and %python_dynlibdir' "$f"
		rc=1
	fi

	# All the rest is related to python modules only.
	printf %s "$rpm_filenames" 2>/dev/null |
		egrep -qs '^/usr/lib(64)?/python[23][.][0-9]/site-packages/' ||
			return $rc

	if [ -n "${rpm_name##python-module-*}" ]; then
		if ! printf %s "$rpm_filenames" 2>/dev/null |
		   egrep -qsv '^/usr/(lib(64)?/python2[.][0-9]/site-packages|share/doc)/'; then
			FileError 'package NAME should start with the "python-module-" prefix' "$f"
			rc=1
		fi
	else
		if printf %s "$rpm_requires" 2>/dev/null | cut -d' ' -f1 |
		   grep -Eqs '^(/usr/bin/)?python3'; then
			FileError 'python2 modules should not have python3 requirements' "$f"
			rc=1
		fi
	fi

	if [ -n "${rpm_name##python3-module-*}" ]; then
		if ! printf %s "$rpm_filenames" 2>/dev/null |
		   egrep -qsv '^/usr/(lib(64)?/python3[.][0-9]/site-packages|share/doc)/'; then
			FileError 'package NAME should start with the "python3-module-" prefix' "$f"
			rc=1
		fi
	else
		if printf %s "$rpm_requires" 2>/dev/null | cut -d' ' -f1 |
		   grep -Eqs '^(/usr/bin/)?python($|[^3])'; then
			FileError 'python3 modules should not have python2 requirements' "$f"
			rc=1
		fi
	fi

	local bad_dirs= noarch_pattern=
	case "$rpm_arch" in
		noarch|i?86|pentium*|athlon*)
			bad_dirs='/usr/lib64/python[23][.][0-9]/site-packages/' ;;
		x86_64|amd64)
			noarch_pattern='^d[^ ]+ /usr/lib/python[23][.][0-9]/site-packages/|^-[^ ]+ /usr/lib/python[23][.][0-9]/site-packages/.*\.py([co])?$'
			bad_dirs='/usr/lib/python[23][.][0-9]/site-packages/' ;;
	esac

	local bad_files=
	if [ -n "$bad_dirs" ]; then
		bad_files="$(printf %s "$rpm_perms_filenames" |
			     egrep "^[^ ]+ $bad_dirs" ||:)"
	fi
	if [ -n "$bad_files" -a -n "$noarch_pattern" ]; then
		bad_files="$(printf %s "$bad_files" |
			     egrep -v "$noarch_pattern" ||:)"
	fi
	if [ -n "$bad_files" ]; then
		bad_files="$(printf %s "$bad_files" |cut -d' ' -f2-)"
		FileError "invalid $rpm_arch python module path: $(oneliner "$bad_files" |fmt -w 128 |head -n1)" "$f"
		rc=1
	fi

	return $rc
}

run_check()
{
	if ! check_python "$1"; then
		CheckError 'python modules packaging violation'
		return 1
	fi
}
