#!/bin/sh

set -eu

echo "Setting up dovecot for the test"
# Move aside 10-auth.conf to disable passwd-based auth
if [ -f /etc/dovecot/conf.d/10-auth.conf ]; then
	mv /etc/dovecot/conf.d/10-auth.conf /etc/dovecot/conf.d/10-auth.conf.bak
fi

cat >/etc/dovecot/local.conf <<-'EOF'
	auth_mechanisms = plain
	mail_driver = maildir
	mail_home = /home/%{user|username}
	mail_path = %{home}/Maildir
	mail_inbox_path = ~/Maildir/.INBOX

	passdb static {
	  passdb_static_password=test
	  fields {
	    user = dep8
	  }
	}

	userdb static {
	  fields {
	    uid = nobody
	    gid = nogroup
	    home = /srv/dovecot-fts-xapian-dep8/%{user|username}
	  }
	}

	protocols = imap

	mail_plugins {
	  fts = yes
	  fts_xapian = yes
	}

	language "en" {
	  default = yes
	}

	fts xapian {
	  verbose = 0
	  maxthreads = 4
	  lowmemory = 500
	  partial = 3
	}

	service decode2text {
	  executable = script /usr/share/doc/dovecot-core/examples/decode2text.sh
	  user = dovecot
	  unix_listener decode2text {
	    mode = 0666
	  }
	}
EOF

mkdir -p /srv/dovecot-fts-xapian-dep8
chown nobody:nogroup /srv/dovecot-fts-xapian-dep8

trap 'set +e; doveconf; journalctl' 0 INT QUIT ABRT PIPE TERM

echo "Restarting the service"
systemctl restart dovecot

echo "Sending a test message via the LDA"
/usr/lib/dovecot/dovecot-lda -f "test@example.com" -d dep8 <<EOF
Return-Path: <test@example.com>
Message-Id: <dep8-test-1@debian.org>
From: Test User <test@example.com>
To: dep8 <dep8@example.com>
Subject: DEP-8 test

Supercalifragilisticexpialidocious
EOF

echo "Verifying that the email was correctly delivered"
if [ -z "$(doveadm search -u dep8 header message-id dep8-test-1@debian.org)" ]; then
	echo "Message not found"
	exit 1
fi

echo "Searching for the email using cURL"
curl --verbose \
     --no-progress-meter \
     --show-error \
     --user 'dep8:test' \
     --request 'SEARCH BODY frag' \
     'imap://localhost/INBOX'

echo "Done"
echo
