#!/bin/sh
# the python compilar
# Authors:
# Donovan Baarda <abo@minkirri.apana.org.au>
# Bastian Kleineidam <calvin@debian.org>

# python command to byte-compile a file
BYTECOMP="import sys,py_compile;py_compile.compile(sys.argv[1],sys.argv[2])"

# compile_pyc </usr/bin/pythonX.Y> <.py> <.pyc>
# byte-compile a single .py file to a 644-chmoded .pyc
compile_pyc () {
    $1 -c "$BYTECOMP" $2 $3
    chmod 0644 $3 || true
}

# compile_pyo </usr/bin/pythonX.Y> <.py> <.pyo>
# byte-compile a single .py file to a 644-chmoded .pyo
compile_pyo () {
    $1 -O -c "$BYTECOMP" $2 $3
    chmod 0644 $3 || true
}

# show help
usage () {
    echo "usage: $0 {compile|compile_opt|remove} <.py file>..."
    exit 1
}


###############################################################
################         main        ##########################
###############################################################
#set -x
action=$1
shift
if echo "$1" | egrep '^python[0-9]\.[0-9]$' >/dev/null 2>&1; then
    PYTHON=/usr/bin/$1
    shift
else
    PYTHON=/usr/bin/python
fi
pyfiles="$*"
if [ "$action" = "compile" ]; then
    for pyfile in $pyfiles; do
        compile_pyc $PYTHON $pyfile ${pyfile}c
    done
elif [ "$action" = "compile_opt" ]; then
    for pyfile in $pyfiles; do
        compile_pyo $PYTHON $pyfile ${pyfile}o
    done
elif [ "$action" = "remove" ]; then
    for pyfile in $pyfiles; do
        rm -f ${pyfile}c ${pyfile}o
    done
else
    usage
fi
