#!/bin/sh
##
## Dovecot: Send a quota warning message to user
## Copyright (c) 2013-2014 SATOH Fumiyas @ OSS Technology Corp., Japan
##               <http://www.OSSTech.co.jp/>
##               <http://fumiyas.github.io/>
##
## License: GNU General Public License version 3
##

set -u

LC_ALL="C"
PATH="/bin:/usr/bin"
export LC_ALL PATH

## ----------------------------------------------------------------------

dovecot_lda="${DOVECOT_LDA:-/opt/osstech/libexec/dovecot/dovecot-lda}"
conf="${DOVECOT_QUOTA_WARNING_CONF:-/opt/osstech/etc/dovecot/quota-warning.conf}"

percent="$1"; shift
user="$1"; shift

user_local="${user%%@*}"
user_domain="${user##*@}"

from="postmaster@$user_domain"
subject="[注意] メールボックス使用量 ${percent}%"
date=`LC_ALL=C date '+%a, %d %b %Y %H:%M:%S %z'`
id="<`date +%s`.$$@$user_domain>"

body="\
$user のメールボックスの使用量が ${percent}% を超えました。
100% を超えるとメールを受信できなくなります。ご注意ください。

-- 
$from
"

if [ -f "$conf" ]; then
  . "$conf" || exit 1
fi

subject_mime=`
  perl \
    -MEncode \
    -e 'Encode::from_to($ARGV[0], "UTF-8", "MIME-Header"); print $ARGV[0]' \
    "$subject" \
    ;
`

## ----------------------------------------------------------------------

cat <<EOT \
|"$dovecot_lda" \
  -d "$user" \
  -o "plugin/quota=maildir:User quota:noenforcing"
From: $from
To: $user
Subject: $subject_mime
Date: $date
Message-Id: $id
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Mailer: $0

$body
EOT

exit 0

