termux_setup_gn() {
	termux_setup_ninja
	local GN_COMMIT=e44942b445d9376451f7d519965dae036efde5bc
	local GN_TARFILE=$TERMUX_COMMON_CACHEDIR/gn_$GN_COMMIT.tar.gz
	local GN_SOURCE=https://gn.googlesource.com/gn/+archive/$GN_COMMIT.tar.gz

	if [ "${TERMUX_PACKAGES_OFFLINE-false}" = "true" ]; then
		GN_FOLDER=$TERMUX_SCRIPTDIR/build-tools/gn-$GN_COMMIT
	else
		GN_FOLDER=$TERMUX_COMMON_CACHEDIR/gn-$GN_COMMIT
	fi

	if [ "$TERMUX_ON_DEVICE_BUILD" = "false" ]; then
		if [ ! -d "$GN_FOLDER" ]; then
			# FIXME: We would like to enable checksums when downloading
			# tar files, but they change each time as the tar metadata
			# differs: https://github.com/google/gitiles/issues/84
			termux_download \
				$GN_SOURCE \
				$GN_TARFILE \
				SKIP_CHECKSUM
			rm -rf "$GN_FOLDER".tmp
			mkdir -p "$GN_FOLDER".tmp
			tar xf $GN_TARFILE -C "$GN_FOLDER".tmp
			local LAST_PWD=$(pwd)
			cd "$GN_FOLDER".tmp
			(
				unset CC CXX CFLAGS CXXFLAGS LD LDFLAGS AR AS CPP OBJCOPY OBJDUMP RANLIB READELF STRIP
				export CC="clang-${TERMUX_HOST_LLVM_MAJOR_VERSION}"
				export CXX="clang++-${TERMUX_HOST_LLVM_MAJOR_VERSION}"
				export LD="clang++-${TERMUX_HOST_LLVM_MAJOR_VERSION}"
				export PATH="/usr/bin:$(echo -n $(tr ':' '\n' <<< "$PATH" | grep -v "^$TERMUX_PREFIX/bin$") | tr ' ' ':')"
				./build/gen.py \
					--no-last-commit-position
				cat <<-EOF >./out/last_commit_position.h
					#ifndef OUT_LAST_COMMIT_POSITION_H_
					#define OUT_LAST_COMMIT_POSITION_H_
					#define LAST_COMMIT_POSITION_NUM 2405
					#define LAST_COMMIT_POSITION "2405 ${GN_COMMIT:0:12}"
					#endif  // OUT_LAST_COMMIT_POSITION_H_
				EOF
				ninja -C out/
			)
			cd $LAST_PWD
			mv "$GN_FOLDER".tmp "$GN_FOLDER"
		fi
		export PATH=$GN_FOLDER/out:$PATH
	else
		if [[ "$(dpkg-query -W -f '${db:Status-Status}\n' gn 2>/dev/null)" != "installed" ]]; then
			echo "Package 'gn' is not installed."
			echo "You can install it with"
			echo
			echo "  pkg install gn"
			echo
			exit 1
		fi
	fi
}
