#!/bin/bash

set -euo pipefail
set -x

export TESTDIR=$(mktemp -d)
echo Using testenv ${TESTDIR}

export SYSTEM=/usr
export LD_LIBRARY_PATH=${SYSTEM}/lib:${SYSTEM}/lib/dovecot:${SYSTEM}/libexec/dovecot
export PATH=${SYSTEM}/bin:${SYSTEM}/sbin:$PATH
export FRONTEND_PORT=1143
export BACKEND_PORT=2143
export RUNAS_USER=$(id -nu)
export RUNAS_GROUP=$(id -ng)

mkdir -p $TESTDIR/frontend $TESTDIR/backend
# common config
envsubst <<EOF | tee $TESTDIR/frontend/dovecot.cfg > $TESTDIR/backend/dovecot.cfg
protocols = imap
listen = *
ssl = no

auth_verbose = yes
mail_debug = yes
auth_debug = yes
auth_debug_passwords = yes
auth_verbose_passwords = yes
disable_plaintext_auth = no
auth_mechanisms = plain

mail_uid = ${RUNAS_USER}
mail_gid = ${RUNAS_GROUP}
default_internal_user = ${RUNAS_USER}
default_internal_group = ${RUNAS_GROUP}
default_login_user = ${RUNAS_USER}
import_environment = SYSTEM PATH LD_LIBRARY_PATH

# some services want to run in a chroot which you can't do if you start as non-root.
service stats {
  chroot =
  unix_listener stats-writer {
    user = ${RUNAS_USER}
    group = ${RUNAS_GROUP}
  }
}
service aggregator {
  chroot =
}
service anvil {
  chroot =
}
service director {
  chroot =
}
service imap-urlauth-login {
  chroot =
}
service ipc {
  chroot =
}
service pop3-login {
  chroot =
}
service indexer-worker {
  chroot =
}

EOF

envsubst <<EOF >> $TESTDIR/frontend/dovecot.cfg
base_dir = ${TESTDIR}/frontend/
state_dir = ${TESTDIR}/frontend/state
log_path = ${TESTDIR}/frontend/dovecot.log
mail_home = ${TESTDIR}/frontend/user_indexes/%u

# frontend proxy
mail_location = imapc:~/imapc
imapc_host = 127.0.0.1
imapc_port = ${BACKEND_PORT}
imapc_ssl = no
imapc_ssl_verify = no

passdb {
  driver = imap
  args = host=127.0.0.1 port=${BACKEND_PORT} username=%u
  default_fields = userdb_imapc_user=%u userdb_imapc_password=%w
}
userdb {
  driver = prefetch
}

service imap-login {
  chroot =
  inet_listener imap {
    address = *
    haproxy = no
    port = ${FRONTEND_PORT}
    reuse_port = no
    ssl = no
  }
}
EOF

envsubst <<EOF >> $TESTDIR/backend/dovecot.cfg
base_dir = ${TESTDIR}/backend/
state_dir = ${TESTDIR}/backend/state
log_path = ${TESTDIR}/backend/dovecot.log
mail_home = ${TESTDIR}/backend/user_indexes/%u
mail_location = maildir:~/Maildir

passdb {
  driver = passwd-file
  args = ${TESTDIR}/backend/virt-passwd
}
userdb {
  driver = static
  args = uid=${RUNAS_USER} gid=${RUNAS_GROUP} home=${TESTDIR}/backend/vmail/%u
}

service imap-login {
  chroot =
  inet_listener imap {
    address = *
    haproxy = no
    port = ${BACKEND_PORT}
    reuse_port = no
    ssl = no
  }
}
EOF

cat > $TESTDIR/backend/virt-passwd <<EOF
user@domain.com:{PLAIN}pass::::::
EOF

# deliver email that causes a crash: there is no body in this email
mkdir -p $TESTDIR/backend/vmail/user@domain.com/Maildir
(cd $TESTDIR/backend/vmail/user@domain.com/Maildir && mkdir -p new cur tmp)
cat > $TESTDIR/backend/vmail/user@domain.com/Maildir/new/$(date +%s) <<EOF
Subject: only headers here

EOF

dovecot -c $TESTDIR/backend/dovecot.cfg
dovecot -c $TESTDIR/frontend/dovecot.cfg

# fetching the snippet of the mail without body through imapc crashes dovecot
cat > test.py <<EOF
import imaplib
conn = imaplib.IMAP4("localhost", 1143)
conn.login("user@domain.com", "pass")
conn.select("INBOX")
try:
    stat, result = conn.fetch("1", "(SNIPPET)")
    print(stats)
    print(result)
except Exception as e:
    print(f"Fail with {type(e)} {e}")
EOF
python3 ./test.py

tail $TESTDIR/frontend/dovecot.log
