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

prog=`basename $0 .bash`
PREFIX=/usr/local
ROLE=toxcore

MOD=gridfire
DIR=$MOD
GIT_HUB=github.com
GIT_USER=reid-k
GIT_DIR=gridfire

DESC=""
[ -f /usr/local/src/usr_local_src.bash ] && \
	. /usr/local/src/usr_local_src.bash 

cd $PREFIX/src || exit 2
WD=$PWD

if [ "$#" -eq 0 ] ; then
    cd $DIR || exit 3

    if [ ! -e $MOD.py ] ; then
	route|grep -q ^default || exit 0
	wget -c https://raw.githubusercontent.com/$GIT_USER/$GIT_DIR/master/$MOD.py
    fi

    #[ -f  $MOD.sh ] || \
	#    cp -p $PREFIX/net/Git/$GIT_HUB/$GIT_USER/$GIT_DIR/$MOD.sh .
    for VER in 2 3 ; do
	PYVER=$VER
	PYTHON_EXE_MSYS=$PREFIX/bin/python$PYVER.bash
	PYTHON_EXE=$PYTHON_EXE_MSYS
	if [ ! -e $PREFIX/bin/$MOD$VER.bash ] ; then
	    cat > $PREFIX/bin/$MOD$VER.bash << EOF
#!/bin/sh
# -*- mode: sh; tab-width: 8; encoding: utf-8-unix -*-
ROLE=$ROLE
# https://$GIT_HUB/$GIT_USER/$GIT_DIR/
exec $PYTHON_EXE_MSYS $PREFIX/src/$DIR/$MOD.py "\$@"
EOF
	    chmod 755 $PREFIX/bin/$MOD$VER.bash
	fi
    done

    # default to python2
    BINS=$MOD
    msys_install_python_scripts $BINS

    cd bin || exit 4
    for file in *.bash *.py ; do
	[ $file = gridfire_ansible-vault.bash ] && continue
	[ -x $PREFIX/bin/$file ] && diff -q $file  $PREFIX/bin/$file && continue
	cp -p $file $PREFIX/bin
	[ -x $PREFIX/bin/$file ] || chmod 775  $PREFIX/bin/$file
    done
    cd ..

    #[ -d /usr/lib64/misc/ ] && [ ! -e /usr/lib64/misc/ssh-askpass ] \
	#  && sudo ln -s $PREFIX/bin/$MOD.bash /usr/lib64/misc/ssh-askpass

    retval=0
    [ -z "$BOX_OS_FLAVOR" ] && BOX_OS_FLAVOR="Linux"
    make all-$BOX_OS_FLAVOR

    OPREFIX=$PREFIX/share/genkernel/overlay
    dist=dist-$BOX_OS_FLAVOR
    [ -d $OPREFIX/bin ] || { sudo mkdir -p $OPREFIX/bin ; sudo chmod 1777 $OPREFIX/bin ; }
    [ ! -x $dist/$MOD ] || \
	[ -x $OPREFIX/bin/$MOD -a $OPREFIX/bin/$MOD -nt $dist/$MOD ] || \
	cp -p $dist/$MOD $OPREFIX/bin/ || exit 9
    # libc.so.1 libz.so.1 libdl.so.1

    exit 0

elif [ "$1" = 'test' ] ; then
    $PREFIX/bin/$MOD.bash --help >/dev/null || exit 10
    make test >/dev/null || exit 11
fi
