#!/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/>.

_docker_name_="$1"

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

if test  "$_docker_name_" = "--help"; then
    echo "Usage:"
    echo "  build-android [DOCKER_NAME]"
    echo ""
    echo "Start this client in the builddir"
    echo "docker-name (optional) is the image name to do the compile in"
    exit
fi

if test -z "$_docker_name_"; then
    _docker_name_="codeberg.org/flowee/buildenv-android:v6.5.3"
fi

floweeSrcDir=`dirname $0`

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$/) { next; } unlink "\$entry"; remove_tree "\$entry"; }'
fi

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
