#!/bin/bash
set -e
set -x

GDB=
if [ $# -gt 0 ]; then
 if [ $1 = "gdb" ]; then
   GDB="gdb --args "
   shift 1
   ARGS="$@"
 else
   ARGS=$*
 fi
fi

#echo "GDB: ${GDB}"
#echo "ARGS: ${ARGS}"
#exit 0

function upfind() {
    dir=`pwd`
    while [ "$dir" != "/" ]; do
	p=`find "$dir" -maxdepth 1 -name $1`
	if [ ! -z $p ]; then
	    echo "$dir"
	    return 
	fi
        dir=`dirname "$dir"`
    done
}

BASEDIR="$(upfind .git)"

# These moved to Makefile, install_openssl target
#rm -f ${BASEDIR}/install_dir/install_dir/openssl.cnf
#ln -s ${BASEDIR}/openssl.cnf ${BASEDIR}/install_dir/install_dir/openssl.cnf

#Debug
#/usr/bin/openssl ${ARGS}
#exit 0

#Works with client/server test application
#n${GDB} ${BASEDIR}/install_dir/bin/openssl ${ARGS}
ARCH=`arch`
if [ ${ARCH} != "armv7l" ]; then
    LD_PRELOAD=/lib/x86_64-linux-gnu/libpthread.so.0 ${GDB} ${BASEDIR}/install_dir/bin/openssl ${ARGS}
else
    LD_PRELOAD=/lib/arm-linux-gnueabihf/libpthread.so.0 ${GDB} ${BASEDIR}/install_dir/bin/openssl ${ARGS}
fi
exit 0

### NOT REACHED ###

# Debug
${BASEDIR}/install_dir/bin/openssl \
    engine ateccx08 \
    ${ARGS}
exit 0

# Command line engine configure, not from openssl.cnf
${BASEDIR}/install_dir/bin/openssl \
    engine dynamic \
    -pre SO_PATH:${BASEDIR}/ecc-crypto/ecc-crypto.so \
    -pre ID:ateccx08 \
    -pre LIST_ADD:1 \
    -pre LOAD \
    ; \
    ${ARGS}