#!/bin/bash
# This file is part of the Flowee project
# Copyright (C) 2022-2023 Tom Zander <tom@flowee.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

_native_dir_="$1"
_docker_name_="$2"

if test -d .bin; then
    ./smartBuild.sh
    exit
fi

if test -z "$_native_dir_"; then
    echo "Usage:"
    echo "  build-android <NATIVEDIR> [DOCKER_NAME]"
    echo ""
    echo "Start this client in the builddir"
    echo "native-dir is the build directory where the hub has been compiled"
    echo "docker-name (optional) is the image name to do the compile in"
    exit
fi

if ! test -d "$_native_dir_"; then
    echo "Native dir not a dir"
    exit
fi
if test -z "$_docker_name_"; then
    _docker_name_="flowee/buildenv-android:v6.4.3"
fi

if ! test -f "$_native_dir_/libs/secp256k1/gen_context"; then
    echo "Invalid or not compiled native dir";
    exit
fi

floweeSrcDir=`dirname $0`

mkdir -p imports
cp $_native_dir_/libs/secp256k1/gen_context imports/

if ! test -f .config; then
    cat << HERE > .config
cd /home/builds/build

if ! test -f build.ninja; then
    cmake \\
        -DCMAKE_TOOLCHAIN_FILE=/opt/android-qt6/lib/cmake/Qt6/qt.toolchain.cmake \\
        -DANDROID_SDK_ROOT=/opt/android-sdk \\
        -DANDROID_NDK_ROOT=/opt/android-ndk \\
        -DOPENSSL_ROOT_DIR=/opt/android-ssl \\
        -DOPENSSL_CRYPTO_LIBRARY=/opt/android-ssl/lib/libcrypto.a \\
        -DOPENSSL_INCLUDE_DIR=/opt/android-ssl/include/ \\
        -G Ninja \\
        -DCMAKE_INSTALL_PREFIX=\`pwd\` \\
        /home/builds/src
fi
HERE
    chmod 755 .config
fi

if ! test -f smartBuild.sh; then
cat << HERE > smartBuild.sh
#!/bin/bash
#Created by build-android.sh

if test "\$1" = "distclean"; then
    perl -e 'use File::Path qw(remove_tree); opendir DIR, "."; while (\$entry = readdir DIR) { if (\$entry=~/^\./) { next; } if (\$entry=~/smartBuild.sh$/ || \$entry=~/^imports$/) { next; } unlink "\$entry"; remove_tree "\$entry"; }'
fi

# use native-build executables
mkdir -p libs/secp256k1/
cp imports/gen_context libs/secp256k1/

if test ! -f build.ninja; then
    docker run --rm --volume=`pwd`:/home/builds/build --volume=$floweeSrcDir:/home/builds/src $_docker_name_  build/.config
fi

docker run --rm --volume=`pwd`:/home/builds/build --volume=$floweeSrcDir:/home/builds/src $_docker_name_ 'ninja -C build install'
HERE
    chmod 700 smartBuild.sh
fi

./smartBuild.sh
