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

prog=`basename $0`
PREFIX=/usr/local
. /usr/local/etc/testforge/testforge.bash
ROLE=pgpkey

PYVER=3
P="BASE_PYTHON${PYVER}_MINOR"
PYTHON_MINOR="$(eval echo \$$P)"
PYTHON_EXE_MSYS=$PREFIX/bin/python$PYVER.bash
PYTHON_EXE=$PYTHON_EXE_MSYS
. /var/local/src/var_local_src.bash || exit 2

cd $PREFIX/src
WD=$PWD

MOD="KeyutilsKeyringBackend"
PKG="python-keyring-keyutils"
VER="0.1"
DIR=$PKG

GIT_HUB=github.com
GIT_USER="marcus-h"
GIT_DIR=$DIR

NET_PREFIX=$PREFIX
HTTP_DIR=$NET_PREFIX/net/Http

URL=github.com/$GIT_USER/$DIR
# https://$GIT_HUB/sassoftware/python-keyutils/archive/0.6.tar.gz

# leave this to ansible
#ols_funtoo_requires sys-apps/keyutils

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

if [ ! -d $DIR ] ; then
    if [ ! -d $NET_PREFIX/net/Git/$GIT_HUB/$GIT_USER/$DIR ] ; then
        ols_are_we_connected || exit 0
	[ -d $NET_PREFIX/net/Git/$GIT_HUB/$GIT_USER/ ] || \
	    mkdir -p $NET_PREFIX/net/Git/$GIT_HUB/$GIT_USER/    
	ols_clone_github || exit 3
    fi

    cp -rip $PREFIX/net/Git/$GIT_HUB/$GIT_USER/$DIR $DIR || exit 4
  fi

cd $DIR || exit 5

#? may need to be in an egg for namespace

if [ ! -f setup.py.dst ] ; then
   ols_setup_zip_unsafe 's@^)@     ,zip_safe=False)@'

   sed -e "s@'keyutils@'keyring_keyutils@" \
	-e 's@ keyutils@ keyring_keyutils@' \
	-e 's@Keyutils/KernelKeyring@KeyringKeyutils/KernelKeyring@' -i \
	setup.py  tests/test_*

fi

#/var/local/lib64/python3.6/site-packages/keyring_keyutils-0.1-py3.6-linux-x86_64.egg
[ -d $PREFIX/$LIB/python$PYTHON_MINOR/site-packages/keyring_keyutils-$VER-py${PYTHON_MINOR}-linux-x86_64.egg ] || \
  msys_python_setup_install 2>&1 \
     || { ERROR $prog $? ; cat install.log ; exit 6 ; }

[ -d "$HTTP_DIR/$GIT_HUB/$GIT_USER/$DIR/" ] || \
    ! ols_are_we_connected || \
    ols_wget_xc -P $HTTP_DIR/ https://$GIT_HUB/$GIT_USER/$DIR/

cd $WD
# "from keyutils.backend import $MOD" 
"$PYTHON_EXE_MSYS" -c \
  "from keyring.core import load_keyring; k=load_keyring('keyring_keyutils.backend.KeyutilsKeyringBackend'); print(dir(k))" || exit 10

[ "$#" -eq 0 ] && exit 0

if [ "$1" = 'test' ] ; then
    cd $PREFIX/src/$DIR || exit 10
    [ -d build/tests ] || cp -rip tests build
    [ -d keyring ] && mv keyring keyring.bak
    # 2 test falures
    cd build || exit 10
    INFO  testing in $PWD
    $PYTHON_EXE_MSYS -m pytest tests >> ../test.log 2>&1 || {
	mv keyring.bak keyring ;
	ERROR "code $?" ; cat ../test.log ; exit 11 ; 
    }
    [ -d keyring.bak ] && mv keyring.bak keyring
    exit 0
fi
mv keyutils keyring_keyutils
