#!/bin/sh
#
# Trigger to compile python code into native bytecode and remove
# generated bytecode files.
#
# Packages need to set the variable pycompile_dirs with a list
# of directories (absolute path) separated by spaces, and WITHOUT
# the first slash, e.g:
#
# pycompile_dirs="usr/blah/foo usr/zoo/d00d"
#
# or if the code resides in standard site-packages directory,
# need to set the pycompile_module variable:
#
# pycompile_module="blah foo"
#
# Or if a module is stored in top-level site-packages directory:
#
# pycompile_module="foo.py"
#
# Additionally another var can be used to specify the target python version:
#
# pycompile_version="3.4"
#
# Arguments:	$ACTION = [run/targets]
#		$TARGET = [post-install/pre-remove]
#		$PKGNAME
#		$VERSION
#		$UPDATE = [yes/no]
#
ACTION="$1"
TARGET="$2"
PKGNAME="$3"
VERSION="$4"
UPDATE="$5"

export PATH="usr/bin:/usr/sbin:/usr/sbin:/usr/bin:/sbin:/bin"

update_ldcache() {
	if [ -x sbin/ldconfig -o -x bin/ldconfig ]; then
		echo "Updating ldconfig(8) cache..."
		ldconfig -X || :
	fi
}

compile()
{
	sitelib="usr/lib/python${pycompile_version}/site-packages"

	# Starting with Python 3.5, compileall supports parallelism
	par=""
	if [ "${pycompile_version%%.*}" -gt 2 ]; then
		pycompile_minor="${pycompile_version#*.}"
		[ "${pycompile_minor}" = "${pycompile_version}" ] && pycompile_minor=""
		if [ -z "${pycompile_minor}" ] || ! [ "${pycompile_minor}" -lt 5 ] >/dev/null 2>&1; then
			par="-j0"
		fi
	fi

	for f in ${pycompile_dirs}; do
		echo "Byte-compiling python code in ${f}..."
		python${pycompile_version} -m compileall ${par} -f -q ./${f} && \
		python${pycompile_version} -O -m compileall ${par} -f -q ./${f}
	done

	for f in ${pycompile_module}; do
		echo "Byte-compiling python${pycompile_version} code for module ${f}..."
		python${pycompile_version} -m compileall ${par} -f -q "${sitelib}/${f}" && \
		python${pycompile_version} -O -m compileall ${par} -f -q "${sitelib}/${f}"
	done

	update_ldcache
}

remove()
{
	sitelib="usr/lib/python${pycompile_version}/site-packages"

	for f in ${pycompile_dirs}; do
		echo "Removing byte-compiled python${pycompile_version} files in ${f}..."
		find ./${f} -type f -name \*.py[co] -delete 2>&1 >/dev/null
		find ./${f} -type d -name __pycache__ -delete 2>&1 >/dev/null
	done

	for f in ${pycompile_module}; do
		echo "Removing byte-compiled python${pycompile_version} code for module ${f}..."
		if [ -d "${sitelib}/${f}" ]; then
			find "${sitelib}/${f}" -type f -name \*.py[co] -delete 2>&1 >/dev/null
			find "${sitelib}/${f}" -type d -name __pycache__ -delete 2>&1 >/dev/null
		else
			rm -f "${sitelib}"/${f%.py}.py[co]
		fi
	done

	update_ldcache
}

case "$ACTION" in
targets)
	echo "post-install pre-remove"
	;;
run)
	[ ! -x usr/bin/python${pycompile_version} ] && exit 0
	[ -z "${pycompile_dirs}" -a -z "${pycompile_module}" ] && exit 0

	case "$TARGET" in
	post-install)
		compile
		;;
	pre-remove)
		remove
		;;
	*)
		exit 1
		;;
	esac
	;;
*)
	exit 1
	;;
esac

exit 0
# end
