#!/bin/bash

# fail hard
set -o pipefail
# fail harder
set -eu

source $(dirname $BASH_SOURCE)/../_util/include/manifest.sh

OUT_PREFIX=$1

dep_formula=${0#$WORKSPACE_DIR/}
dep_name=$(basename $BASH_SOURCE)
dep_version=${dep_formula##*"/${dep_name}-"}
dep_package=pkg-${dep_name}-${dep_version}
dep_dirname=uw-imap-${dep_version}~dfsg
dep_urls=(
	http://archive.ubuntu.com/ubuntu/pool/universe/u/uw-imap/uw-imap_${dep_version}~dfsg.orig.tar.gz
)
if [[ $STACK == "cedar-14" ]]; then
	dep_urls+=(
		http://archive.ubuntu.com/ubuntu/pool/universe/u/uw-imap/uw-imap_${dep_version}~dfsg-2.debian.tar.gz
		http://archive.ubuntu.com/ubuntu/pool/universe/u/uw-imap/uw-imap_${dep_version}~dfsg-2.dsc
	)
elif [[ $STACK == "heroku-16" ]]; then
	dep_urls+=(
		http://archive.ubuntu.com/ubuntu/pool/universe/u/uw-imap/uw-imap_${dep_version}~dfsg-4.debian.tar.xz
		http://archive.ubuntu.com/ubuntu/pool/universe/u/uw-imap/uw-imap_${dep_version}~dfsg-4.dsc
	)
elif [[ $STACK == "heroku-18" ]]; then
	dep_urls+=(
		http://archive.ubuntu.com/ubuntu/pool/universe/u/uw-imap/uw-imap_${dep_version}~dfsg-5build1.debian.tar.xz
		http://archive.ubuntu.com/ubuntu/pool/universe/u/uw-imap/uw-imap_${dep_version}~dfsg-5build1.dsc
	)
fi
dep_destname=imap-${dep_version}
dep_manifest=${dep_package}.composer.json

echo "-----> Building ${dep_package}..."

# we need that for IMAP
needed=( libpam0g-dev )
if [[ $STACK == "cedar-14" ]]; then
	gpg --keyserver keyserver.ubuntu.com --recv-keys 7D61E3E6
	gpg --no-default-keyring -a --export 7D61E3E6 | gpg --no-default-keyring --keyring ~/.gnupg/trustedkeys.gpg --import -
else
	needed+=( debian-keyring )
fi
missing=$(comm -1 -3 <(dpkg-query -W -f '${package}\n' | sort) <(IFS=$'\n'; echo "${needed[*]}" | sort))
if [[ "$missing" ]]; then
	apt-get update -qq || { echo "Failed to 'apt-get update'. You must build this formula using Docker."; exit 1; }
	apt-get install -q -y $missing
fi

curl -L --remote-name-all "${dep_urls[@]}"

dpkg-source --require-valid-signature -x $(basename ${dep_urls[-1]})

pushd ${dep_dirname}

# SNI capabilities for libc-client; some servers (GMail) require it with TLSv1.3, which OpenSSL 1.1.1 supports
patch -p1 <<EOF
--- a/src/osdep/unix/ssl_unix.c
+++ b/src/osdep/unix/ssl_unix.c
@@ -273,6 +273,17 @@ static char *ssl_start_work (SSLSTREAM *stream,char *host,unsigned long flags)
 				/* create connection */
   if (!(stream->con = (SSL *) SSL_new (stream->context)))
     return "SSL connection failed";
+#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
+  ASN1_OCTET_STRING *ip;
+  /* support SNI if host is not an IP address */
+  /* per RFC 6066: */
+  /* Literal IPv4 and IPv6 addresses are not permitted in "HostName". */
+  ip = a2i_IPADDRESS(host);
+  if (ip == NULL) {
+    ERR_clear_error();
+    SSL_set_tlsext_host_name(stream->con,host);
+  }
+#endif
   bio = BIO_new_socket (stream->tcpstream->tcpsi,BIO_NOCLOSE);
   SSL_set_bio (stream->con,bio,bio);
   SSL_set_connect_state (stream->con);
EOF

touch ip6 # so we do not get prompted
make ldb EXTRACFLAGS=-fPIC # need PIC so relocations work in the shared imap.so ext later
mkdir -p ${OUT_PREFIX}/opt/${dep_destname}/include ${OUT_PREFIX}/opt/${dep_destname}/lib
cp c-client/*.h ${OUT_PREFIX}/opt/${dep_destname}/include
cp c-client/*.c ${OUT_PREFIX}/opt/${dep_destname}/lib
cp c-client/*.a ${OUT_PREFIX}/opt/${dep_destname}/lib
strip --strip-unneeded ${OUT_PREFIX}/opt/${dep_destname}/lib/*.a
popd

python $(dirname $BASH_SOURCE)/../_util/include/manifest.py "heroku-sys-package" "heroku-sys/pkg-${dep_name}" "$dep_version" "${dep_formula}.tar.gz" > $dep_manifest

print_or_export_manifest_cmd "$(generate_manifest_cmd "$dep_manifest")"
