###
### Meta Information
###
FROM localhost/debian

# deploy options
# -p (port) and -v (volume) both go host:container
LABEL config_default="\
-p 25:25 \
-p 587:587 \
-p 143:143 \
-p 993:993 \
-v /srv/vol/mailsrv/data:/vol/data \
-v /srv/vol/mailsrv/mail:/vol/mail \
-v /srv/vol/mailsrv/ssl:/vol/ssl:ro \
-v /srv/vol/mailsrv/log:/vol/log \
"

# Build Variables
# uid that the files owner user should have
ARG FILESUID=5000

###
### General Setup
###

# tell debian not to ask questions during install process
ARG DEBIAN_FRONTEND=noninteractive

# install packages we want
RUN apt update -y && apt install -y rsyslog postfix dovecot-imapd dovecot-lmtpd dovecot-sieve cron

# add virtual mail user
RUN addgroup --gid ${FILESUID:?} vmail && \
    adduser vmail --ingroup vmail --uid ${FILESUID:?} --disabled-password --gecos "Virtual Mail Owner" --shell /usr/sbin/nologin --no-create-home --home /var/mail/virtual

# copy our custom scripts
COPY assets/bin /usr/local/bin

# put restart job in system crontab
RUN echo '# restart postfix and dovecot every Monday at 3AM' >> /etc/crontab && \
    echo '23 3    * * 1   root    systemctl restart postfix && systemctl restart dovecot' >> /etc/crontab

# replace /var/log with symlink to /vol/log
RUN mkdir -p /vol/log && \
    rm -r /var/log && \
    ln -s /vol/log /var/log

###
### mkvirtual
###

# copy mkvirtual service
COPY assets/mkvirtual.service /etc/systemd/system/

# enable service
RUN systemctl enable mkvirtual.service

###
### Postfix
###

# copy postfix config
COPY assets/postfix /etc/postfix

###
### Dovecot
###

# copy dovecot config
COPY assets/dovecot /etc/dovecot

# make symlink to mail dir
RUN ln -s /vol/mail /var/mail/virtual

###
### Working Directory
###

# make sure /vol/data exists
RUN mkdir -p /vol/data

# set /vol/data as working directory
WORKDIR /vol/data

###
### Bugfix
###

# bugfix for cron
COPY bugfix/cronfix /root/
RUN chmod +x /root/cronfix && /root/cronfix