FROM alpine/git:2.47.2@sha256:062a01ad7a0eb17cff382bc5e26086b4d710e56dfdfdf001109a49b6d9bd378c AS imapsync-source

ARG IMAPSYNC_REV=93654c6025ff7814f983ab74dd300f9bed9282d9
RUN git clone https://github.com/imapsync/imapsync.git /src \
    && git -C /src checkout "$IMAPSYNC_REV" \
    && test "$(git -C /src rev-parse HEAD)" = "$IMAPSYNC_REV"

FROM perl:5.38-slim

LABEL maintainer="Hoelee <me@hoelee.com>"
LABEL description="Multi-account IMAP sync with OAuth2 support for Office 365, Hotmail, Outlook.com, and Gmail"

# Install imapsync + dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    libauthen-ntlm-perl \
    libdbd-sqlite3-perl \
    libdist-checkconflicts-perl \
    libfile-copy-recursive-perl \
    libemail-address-perl \
    libhttp-daemon-ssl-perl \
    libio-compress-perl \
    libio-socket-inet6-perl \
    libio-socket-ssl-perl \
    libio-tee-perl \
    libjson-pp-perl \
    libmail-imapclient-perl \
    libmodule-runtime-perl \
    libnet-dbus-perl \
    libnet-dns-perl \
    libpackage-stash-perl \
    libpar-dist-perl \
    libproc-processtable-perl \
    libproc-simple-perl \
    libregexp-common-perl \
    libssl-dev \
    libtest-fatal-perl \
    libtest-mock-guard-perl \
    libtest-nowarnings-perl \
    libtest-pod-perl \
    libtest-requires-perl \
    libtest-simple-perl \
    libunicode-string-perl \
    liburi-perl \
    libwww-perl \
    cron \
    msmtp \
    netcat-openbsd \
    procps \
    && rm -rf /var/lib/apt/lists/*

# Install one immutable, verified upstream revision of imapsync and its current
# OAuth helper. The old helper URLs no longer exist upstream.
COPY --from=imapsync-source /src/imapsync /usr/local/bin/imapsync
COPY --from=imapsync-source /src/oauth2/oauth2_imap/oauth2_imap /usr/local/bin/oauth2_imap
RUN chmod +x /usr/local/bin/imapsync /usr/local/bin/oauth2_imap

# Copy entrypoint
COPY sync.sh /sync.sh
RUN chmod +x /sync.sh

# Health is liveness plus notification delivery. Sync freshness is exposed by
# accountN.last_success / accountN.last_failure files for the chosen schedule.
HEALTHCHECK --interval=5m --timeout=10s --start-period=60s --retries=3 \
    CMD test -f "${LOG_DIR:-/var/log/imapsync}/.heartbeat" && \
        test ! -f "${LOG_DIR:-/var/log/imapsync}/.notification_failed" && \
        test "$(cat "${LOG_DIR:-/var/log/imapsync}/.heartbeat")" -gt "$(date -d '5 minutes ago' +%s)" || \
        { echo "Health check failed: daemon heartbeat is stale or SMTP notification delivery failed. Check container logs."; exit 1; }

ENTRYPOINT ["/sync.sh"]
