#!/usr/bin/env bash
set -e
if [ -z "$O3" ]; then
    echo O3 var must point to ovpn3 tree
    exit 1
fi
if [ -z "$TARGET" ]; then
    echo TARGET var must be defined
    exit 1
fi
if [ -z "$OPENSSL_TARGET" ]; then
    echo "OPENSSL_TARGET var must be defined"
    exit 1
fi

# GNU sed differs from BSD sed
if sed --version 2>&1 | grep -q GNU ; then
    mysed='sed -i'
else
    mysed='sed -i ""'
fi

[ -z "$GCC_CMD" ] && GCC_CMD=gcc

[ -z "$LINK_MODE" ] && LINK_MODE=static
[ "$LINK_MODE" = "static" ] && LINK_MODE=no-shared

[ -z "$DL" ] && DL=~/Downloads

. $O3/core/vars/vars-$TARGET
. $O3/core/deps/lib-versions


# source vars
. $O3/core/vars/vars-${TARGET}
. $O3/core/deps/lib-versions

# source helper functions
. $O3/core/deps/functions.sh

FNAME=openssl-${OPNESSL_VERSION}.tar.gz
URL=https://www.openssl.org/source/${OPENSSL_VERSION}.tar.gz
CSUM=${OPENSSL_CSUM}

download

AR=ar
RANLIB=ranlib
[ "$AR_CMD" ] && AR=$AR_CMD
[ "$RANLIB_CMD" ] && RANLIB=$RANLIB_CMD

# special hack because OpenSSL build system doesn't use rc options for ar
[ "$AR" = "gcc-ar" ] && AR="gcc-ar rc"
[ "$AR" = "gcc-ar-5" ] && AR="gcc-ar-5 rc"

OPENSSL=$OPENSSL_VERSION
DIST=$(pwd)/openssl/openssl-$PLATFORM
[ "$ARCH" ] && DIST=$DIST/$ARCH
rm -rf $OPENSSL $DIST
mkdir -p $DIST
tar xfz $DL/$FNAME
pushd $OPENSSL
CMD="./Configure $OPENSSL_TARGET $LINK_MODE threads no-idea no-mdc2 no-rc5 --prefix=$DIST"
echo $CMD
$CMD
$mysed -e "s|-O3|$LIB_OPT_LEVEL $MIN_DEPLOY_TARGET $OTHER_COMPILER_FLAGS $LIB_FPIC|" Makefile
#$mysed -e "s|ERR_load_COMP_strings()|//ERR_load_COMP_strings()|" crypto/err/err_all.c
make depend
make CC="$GCC_CMD" AR="$AR" RANLIB="$RANLIB" -j ${MAKE_JOBS:-1} build_libs
touch apps/openssl
touch openssl.pc
touch libcrypto.pc
touch libssl.pc
make install_sw
popd

exit 0
