1#!/bin/sh
2# android shell
3
4if [ -n "$1" ]; then
5	NDK_ARCH="$1"
6	shift
7fi
8export ANDROID=1
9ARCH=${NDK_ARCH}
10case "${NDK_ARCH}" in
11mips64)
12	export NDK_ARCH
13	AR=mips64el-linux-android-ar
14	RANLIB=mips64el-linux-android-ranlib
15	;;
16mips)
17	export NDK_ARCH
18	AR=mipsel-linux-android-ar
19	RANLIB=mipsel-linux-android-ranlib
20	;;
21x64)
22	NDK_ARCH=x86_64
23	export NDK_ARCH
24	;;
25x86|x86_64)
26	export NDK_ARCH
27	;;
28aarch64|arm64)
29	NDK_ARCH=aarch64
30	export NDK_ARCH
31	AR=aarch64-linux-android-ar
32	ARCH=arm64
33	RANLIB=aarch64-linux-android-ranlib
34	;;
35arm)
36	export NDK_ARCH
37	AR=arm-linux-androideabi-ar
38	RANLIB=arm-linux-androideabi-ranlib
39	;;
40local)
41	export ANDROID=1
42	;;
43*)
44	echo "Usage: $0 [arm64|arm|mips|mips64|x86|x64]"
45	exit 1
46	;;
47esac
48
49LANG=C
50export LANG
51ROOT=`dirname $0`
52OS=`uname|tr 'A-Z' 'a-z'`
53[ "${OS}" = macosx ] && OS=darwin
54
55if [ ! -x /work ]; then
56	echo "Building android locally with NDK instead of dockcross..."
57	# TODO: autodetect or gtfo
58	if [ -f ~/.r2androidrc ]; then
59		. ~/.r2androidrc
60		echo "Using data from ${HOME}/.r2androidrc.."
61	else
62		#[ -z "${SDK}" ] && SDK="${HOME}/Downloads/android-sdk-${OS}"
63		if [ -z "${NDK}" ]; then
64			# Checking if Android NDK is installed with macOS's brew
65			D=/usr/local/Caskroom/android-ndk/
66			if [ -d "${D}" ]; then
67				for a in $(cd "$D" && ls) ; do
68					N="$D/$a/android-ndk-r$a"
69					if [ -f "$N/README.md" ]; then
70						NDK="$N"
71						break
72					fi
73				done
74			fi
75		fi
76		if [ -z "${NDK}" ]; then
77			if [ "`uname`" = "Darwin" ]; then
78				NDK="${HOME}/Library/Android/sdk/ndk-bundle/"
79			else
80				NDK="${HOME}/Downloads/android-ndk-r21d"
81			fi
82		fi
83		[ -z "${NDK}" ] && NDK="${HOME}/Downloads/android-ndk-r21d"
84	fi
85fi
86
87echo ROOT=$ROOT
88echo NDK="$NDK"
89echo NDK_ARCH=$NDK_ARCH
90
91if [ -x /tmp/ndk/bin/ndk-gcc ]; then
92	echo "NDK toolchain already initialized."
93else
94	echo "Building the standalone NDK toolchain..."
95	${NDK}/build/tools/make_standalone_toolchain.py --arch=${ARCH} --install-dir=/tmp/ndk/ --api=28 --force
96	(
97	cd /tmp/ndk/bin/ && \
98	ln -fs clang ndk-gcc && \
99	ln -fs clang++ ndk-g++
100	)
101fi
102if [ "${BUILD}" != 0 ]; then
103	if [ ! -d "${NDK}" ]; then
104		echo "Cannot find Android NDK ${NDK}" >&2
105		echo "echo NDK=/path/to/ndk  > ~/.r2androidrc" >&2
106		exit 1
107	fi
108	PATH="/tmp/ndk/bin:$PATH"
109	export PATH
110	export CFLAGS
111	export NDK
112	export NDK_ARCH
113	[ -z "${SHELL}" ] && SHELL=sh
114	SHELL=sh
115	CC=ndk-gcc
116	CXX=ndk-g++
117	PS1="[r2-android-${NDK_ARCH}]> "
118	export CC
119	export CXX
120	export PS1
121	export AR
122	export RANLIB
123	A=$@
124	if [ -n "$A" ]; then
125		${SHELL} -c "$A"
126	else
127		${SHELL}
128	fi
129fi
130