#!/bin/sh

python_interpreter="python"
paths=""

while [ $# -gt 0 ]; do
	case "${1}" in
		--python=*)
			python_interpreter=${1#--python=}
			;;
		*)
			paths="${paths} ${1}"
			;;
	esac
	shift
done

if [ -z "${paths}" ]; then
	echo >&2 "No path specified!"
	exit 1
fi

if [ "${python_interpreter:0:1}" != "/" ]; then
	python_interpreter=$(which ${python_interpreter} 2>/dev/null)
fi

if [ ! -x "${python_interpreter}" ]; then
	echo >&2 "Python interpreter is not executable: ${python_interpreter}"
	exit 1
fi

tempfile=$(mktemp)
trap "rm -f ${tempfile}" EXIT

cat > ${tempfile} <<EOF
import os
import py_compile
import sys

for file in sys.argv[1:]:
	if not os.path.exists(file):
		continue

	py_compile.compile(file, doraise=0)
EOF

filelist=$(find ${paths} -type f -a -name "*.py" 2>/dev/null)

# Compile with optimization.
${python_interpreter} -O ${tempfile} ${filelist}

# Compile without optimization.
${python_interpreter} ${tempfile} ${filelist}

# Hardlink identical files.
for pyc in $(find ${paths} -type f -a -name "*.pyc" 2>/dev/null); do
	pyo="${pyc/.pyc/.pyo}"

	if cmp -s "${pyc}" "${pyo}"; then
		ln -f "${pyc}" "${pyo}"
	fi
done
