docker-images/images/imap-download/run.sh

76 lines
2.1 KiB
Bash
Raw Normal View History

2021-05-25 21:19:37 +00:00
#!/usr/bin/env bash
dir_newmail="/tmp/maildir/Mail/new";
target_dir="/mnt/output";
fetchmail_uid="$(id -u "fetchmail")";
fetchmail_gid="$(id -g "fetchmail")";
2021-05-25 21:19:37 +00:00
temp_dir="$(mktemp --tmpdir -d "imap-download-XXXXXXX")";
on_exit() {
rm -rf "${temp_dir}";
}
trap on_exit EXIT;
do_fetchmail() {
log_msg "Starting fetchmail";
while :; do
# Ref https://github.com/SinusBot/docker/pull/40
# WORKAROUND for `setpriv: libcap-ng is too old for "all" caps`, previously "-all" was used here
# create a list to drop all capabilities supported by current kernel
cap_prefix="-cap_";
caps="$cap_prefix$(seq -s ",$cap_prefix" 0 "$(cat /proc/sys/kernel/cap_last_cap)")";
setpriv --inh-caps="${caps}" --reuid "${fetchmail_uid}" --clear-groups --regid "${fetchmail_gid}" fetchmail --mda "/usr/bin/procmail -m /srv/procmail.conf";
exit_code="$?";
if [[ "$exit_code" -eq 127 ]]; then
log_msg "setpriv failed, exiting with code 127";
exit 127;
fi
log_msg "Fetchmail exited with code ${exit_code}, sleeping 60 seconds";
sleep 60
done
2021-05-25 21:19:37 +00:00
}
log_msg() {
echo "$(date -u +"%Y-%m-%d %H:%M:%S") imap-download: $*";
}
mkdir -p "${dir_newmail}";
2021-05-25 21:19:37 +00:00
do_attachments() {
while :; do # : = infinite loop
# Wait for an update
# inotifywait's non-0 exit code forces an exit for some reason :-/
inotifywait -qr --event create --format '%:e %f' "${dir_newmail}";
while read -r filename; do
log_msg "Processing email ${filename}";
# Move the email to a temporary directory for processing
mv "${filename}" "${temp_dir}";
# Unpack the attachments
munpack -C "${temp_dir}" "${filename}";
# Delete the original email file and any description files
rm "${filename}";
find "${temp_dir}" -iname '*.desc' -delete;
# Move the attachment files to the output directory
while read -r attachment; do
log_msg "Extracted attachment ${attachment}";
chmod 0775 "${temp_dir}/${attachment}";
2021-05-25 21:19:37 +00:00
mv "${attachment}" "${target_dir}";
2021-05-25 21:19:37 +00:00
done < <(find "${temp_dir}" -type f);
done < <(find "${dir_newmail}" -type f);
done
}
do_fetchmail &
do_attachments