#!/bin/sh

set -e

echo "Setting up postgres resources"
# runuser -u postgres -- createuser dovecot
# runuser -u postgres -- createdb -O dovecot dovecot
cat <<EOF | mysql
CREATE DATABASE dovecot;
CREATE USER dovecot;
GRANT ALL ON dovecot.* TO 'dovecot'@'%' IDENTIFIED BY 'test';
USE dovecot;
CREATE TABLE users (
    userid VARCHAR(128) NOT NULL,
    domain VARCHAR(128) NOT NULL,
    password VARCHAR(64) NOT NULL,
    home VARCHAR(255) NOT NULL,
    uid INTEGER NOT NULL,
    gid INTEGER NOT NULL
);
insert into users values(
       'dep8',
       'example.com',
       'test',
       '/srv/dovecot-dep8',
       65534,
       65534
);
EOF

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
sql_driver = mysql

# The mysqld.sock socket may be in different locations in different systems.
mysql /run/mysqld/mysqld.sock {
  user = dovecot
  password = test
  dbname = dovecot

  #ssl = yes
  #ssl_client_ca_dir = /etc/ssl/certs
}
# Alternatively you can connect to localhost as well:
#mysql localhost {
#}

passdb sql {
  query = SELECT userid AS username, domain, password \
    FROM users \
    WHERE userid = '%{user | username}' AND domain = '%{user | domain}'
}
userdb sql {
  query = SELECT home, uid, gid \
    FROM users \
    WHERE userid = '%{user | username}' AND domain = '%{user | domain}'
  # For using doveadm -A:
  iterate_query = SELECT userid AS username, domain FROM users
}
EOF

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

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@example.com <<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

This is just a test
EOF

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

echo "Done"
echo
