#!/bin/bash

set -e

if [[ "${TARGET_PRODUCT}" != "aosp_arm" ]]; then
  # Some of the include paths below assume that this is an arm 32bit configure
  # run.
  echo "Run 'lunch aosp_arm-eng' and build the current version first." >&2
  exit 1
fi

cd $(dirname "$0")

HOST="arm-linux-androideabi"
export CC="${ANDROID_TOOLCHAIN}/${HOST}-gcc"
export LD="${ANDROID_TOOLCHAIN}/${HOST}-ld"

T="${ANDROID_BUILD_TOP}"
CFLAGS=(
  "-isystem ${T}/external/libcxx/include"
  "-isystem ${T}/bionic/libc/include/"
  "-isystem ${T}/bionic/libc/arch-arm/include"
  "-isystem ${T}/bionic/libc/kernel/android/uapi/"
  "-isystem ${T}/bionic/libc/kernel/uapi/"
  "-isystem ${T}/bionic/libc/kernel/uapi/asm-arm/"
  "-isystem ${T}/bionic/libm/include"
  "-isystem ${T}/build/core/combo/include/arch/linux-arm/"
  "-fno-exceptions"
  "-ffunction-sections"
  "-fdata-sections"
  "-fstack-protector"
  "-fno-short-enums"
  "-no-canonical-prefixes"
  "-fmessage-length=0"
  "-fomit-frame-pointer"
  "-fPIC"
  "-fno-strict-aliasing"
  "-nostdlib"
)
CFLAGS="${CFLAGS[@]}"

CONFIGURE_ARGS=(
  --host="${HOST}"
  CFLAGS="${CFLAGS}"
  LIBS="-lc"
  CPPFLAGS="${CFLAGS} -I${T}/external/zlib/src"
  LDFLAGS="-L${ANDROID_PRODUCT_OUT}/system/lib/"

  # Disable NTLM delegation to winbind's ntlm_auth.
  --disable-ntlm-wb

  ### Disable many protocols unused in Android systems:
  --disable-telnet
  --disable-tftp
  --disable-smb
  --disable-gopher

  # Disable FTP and FTPS support.
  --disable-ftp

  # Disable LDAP and LDAPS support.
  --disable-ldap
  --disable-ldaps

  # Disable mail protocols (IMAP, POP3).
  --disable-pop3
  --disable-imap
  --disable-smtp

  # Disable RTSP support (RFC 2326 / 7826).
  --disable-rtsp

  # Disable DICT support (RFC 2229).
  --disable-dict


  ### Enable HTTP, FTP and FILE explicitly. These are enabled by default but
  # listed here as documentation.
  --enable-http
  --enable-file
  --enable-proxy

  # Enabled IPv6.
  --enable-ipv6

  --with-ssl="${T}/external/boringssl"
  --with-zlib
  --with-ca-path="/system/etc/security/cacerts"
)

# Show the commands on the terminal.
set -x

./buildconf
./configure "${CONFIGURE_ARGS[@]}"

# Apply local changes to the default configure output.
patch -p1 --no-backup-if-mismatch < local-configure.patch