#!/bin/sh

#
# Copyright 2019-2021 Signal Messenger, LLC
# SPDX-License-Identifier: AGPL-3.0-only
#

set -e

# this could also be:
# - a gclient hook
# - a build step for ringrtc/BUILD.gn, putting the correct NDK in the output directory

BIN_DIR="$(realpath -e $(dirname $0))"
. "${BIN_DIR}/env.sh"

rm -rf "$NDK_TOOLCHAIN_INSTALL_DIR"

# where is the NDK located?
NDK_HOME="${WEBRTC_DIR}/src/third_party/android_ndk"

[ -d "$NDK_HOME" ] || {
    echo "ERROR: unable to find NDK directory: $NDK_HOME"
    exit 1
}

# what NDK API version do we want?  21 is the minimum to support arm64
# and x86_64.  Keep this in sync with WebRTC's src/.gn file (around
# line 70) and Signal-Android-Private API minimums:
#
#   android32_ndk_api_level = 19
#   android64_ndk_api_level = 21

NDK_32=19
NDK_64=21

# what architectures to install?
ARCHS="
arm
arm64
x86
x86_64
"

CARGO_CONFIG_DIR=src/rust/.cargo
CARGO_CONFIG="${CARGO_CONFIG_DIR}/config"
if [ -f $CARGO_CONFIG ] ; then
    BACKUP_CARGO=$(mktemp -u -p $CARGO_CONFIG_DIR -t config.XXXXXXXX.bak)
    echo "I: cargo config exists already, renaming to: $BACKUP_CARGO."
    mv -f $CARGO_CONFIG $BACKUP_CARGO
else
    echo "I: generating cargo config for toolchains."
fi
mkdir -p $(dirname $CARGO_CONFIG)

rm -f $NDK_ENV
mkdir -p $(dirname $NDK_ENV)
cat <<"EOF" > $NDK_ENV
#!/bin/sh

# shell environment variables for adding NDK toolchains to $PATH

unset NDK_PATH

EOF

for a in $ARCHS ; do
    ARCH_INSTALL_DIR="${NDK_TOOLCHAIN_INSTALL_DIR}/$a"

    case "$a" in
        arm)
            target=arm-linux-androideabi
            NDK="$NDK_32"
            ;;
        arm64)
            target=aarch64-linux-android
            NDK="$NDK_64"
            ;;
        x86)
            target=i686-linux-android
            NDK="$NDK_32"
            ;;
        x86_64)
            target=x86_64-linux-android
            NDK="$NDK_64"
            ;;
        *)
            echo "ERROR: Unknown architecture: $a"
            exit 1
    esac

    echo "I: Installing NDK-${NDK} toolchain for arch: $a --> $ARCH_INSTALL_DIR ..."
    # Use the LLVM libc++, which is what WebRTC is using.
    ${NDK_HOME}/build/tools/make_standalone_toolchain.py \
               --api $NDK \
               --stl libc++ \
               --arch $a \
               --install-dir "$ARCH_INSTALL_DIR"

    linker=$(realpath -e "${ARCH_INSTALL_DIR}/bin/${target}-clang")
    ar=$(realpath -e "${ARCH_INSTALL_DIR}/bin/${target}-ar")
    cat <<EOF >> $CARGO_CONFIG
[target.$target]
linker = "$linker"
ar = "$ar"

EOF

    cat <<EOF >> $NDK_ENV
NDK_PATH="\${NDK_PATH:+\${NDK_PATH}:}$(realpath -e ${ARCH_INSTALL_DIR}/bin)"
EOF

done
