#!/bin/sh
# -*-mode: sh; tab-width: 8; coding: utf-8-unix -*-

. /usr/local/bin/usr_local_base.bash || exit 2
PREFIX=/usr/local
ROLE=base

[ -z "$BASE_PYTHON2_MINOR" ] && \
    BASE_PYTHON2_MINOR=$( python2 --version 2>&1| sed -e 's@^.* @@' -e 's@\.[0-9]*$@@' )
[ -z "$BASE_PYTHON3_MINOR" ] && \
    BASE_PYTHON3_MINOR=$( python3 --version 2>&1| sed -e 's@^.* @@' -e 's@\.[0-9]*$@@' )

for PYTHON_MINOR in "$BASE_PYTHON2_MINOR" "$BASE_PYTHON3_MINOR" ; do
    [ -z "$PYTHON_MINOR" ] && continue
if [ -z "$LIB" -a -d /usr/lib/python$PYTHON_MINOR/site-packages ] ; then
    LIB=lib
elif [ -z "$LIB" -a -d /usr/lib64/python$PYTHON_MINOR/site-packages ] ; then
    LIB=lib64
elif [ -n "$LIB" -a ! -d /usr/$LIB/python$PYTHON_MINOR/site-packages ] ; then
    ERROR LIB=$LIB but no /usr/$LIB/python$PYTHON_MINOR/site-packages
fi
done

umask 0022
# [ "$#" -eq 0 ] && set --  $PREFIX/bin

# FixMe? /usr/local/bin too? I think not, except for ours?

for prefix in /usr/local /var/local ; do
    cd $prefix/bin || exit 1
    #? ls -1d * | grep -v '~' | xargs file | grep -i python | sed -e 's/:.*//'|while read file ; do
    ls -1 | grep -v '~' | xargs file | grep script | sed -e 's/:.*//' | \
      while read file ; do
	head -1 $file | grep -q python || continue
	head -1 $file | grep -q $prefix/python..bash && continue
	base=$( echo $file | sed -e 's/\.bash$//' )
	under=$( echo $prefix | sed -e 's/^.//' -e 's@/@_@g' )
	if [ -h /etc/python-exec/$base.conf ] ; then
	    link=$( readlink /etc/python-exec/$base.conf )
	    if [ "$link" = python2.conf ] ; then
		sed -f $prefix/share/sed/${under}_python2.sed -i $file
	    else
		sed -f $prefix/share/sed/${under}_python3.sed -i $file
	    fi
	else
	    sed -f $prefix/share/sed/${under}_python2.sed -i $file
	    sed -f $prefix/share/sed/${under}_python3.sed -i $file
	fi
	#    echo $file
    done

    # failsafe - Eberly - no longer active
    for elt in $BASE_PYTHON2_MINOR $BASE_PYTHON3_MINOR ; do
	[ -f $prefix/${LIB}/python$elt/site-packages/site.py ]
 	    # WARN missing $prefix/${LIB}/python$elt/site-packages/site.py
    done

done

exit 0
