#!/usr/local/bin/perl
# Send email to users approaching their quotas

$no_acl_check++;
require './quota-lib.pl';
&foreign_require("mailboxes", "mailboxes-lib.pl");

# Find filesystems with quotas
foreach $fs (&list_filesystems()) {
	if ($fs->[4] && $fs->[5]) {
		$fslist{$fs->[0]}++;
		}
	}

# Look for filesystems with warning enabled
$now = time();
foreach $k (keys %config) {
	if ($k =~ /^email_(\S+)$/ && $fslist{$1}) {
		# Found a filesystem to check
		$f = $1;
		$n = &filesystem_users($f);
		local %emailtimes;
		local $qf = $f;
		$qf =~ s/\//_/g;
		&read_file("$module_config_directory/emailtimes.$qf",
			   \%emailtimes);
		$interval = $config{'email_interval_'.$f}*60*60;

		for($i=0; $i<$n; $i++) {
			if ($config{'email_type_'.$f}) {
				$limit = $user{$i,'hblocks'};
				}
			else {
				$limit = $user{$i,'sblocks'};
				}
			next if (!$limit);

			# Check if over threshold
			$upercent = 100.0*$user{$i,'ublocks'}/$limit;
			next if ($upercent < $config{'email_percent_'.$f});

			# Check if time to email
			next if ($emailtimes{$user{$i,'user'}} >=
				 $now - $interval);

			# Email the user
			&send_quota_mail(
				$user{$i,'user'},
				$config{'email_domain_'.$f},
				$limit,
				$user{$i,'ublocks'},
				$f,
				$upercent,
				$config{'email_from_'.$f},
				);

			# Save last email time
			$emailtimes{$user{$i,'user'}} = $now;
			}

		&write_file("$module_config_directory/emailtimes.$qf",
			    \%emailtimes);
		}
	}

sub send_quota_mail
{
local ($user, $dom, $limit, $used, $fs, $percent, $from) = @_;
print STDERR "sending email to $user\n";
local $bsize = &block_size($fs);
if ($bsize) {
	$used = &nice_size($used*$bsize);
	$limit = &nice_size($limit*$bsize);
	}
else {
	$used = "$used blocks";
	$limit = "$limit blocks";
	}
local $addr = $user =~ /\@/ ? $user : $user.'@'.$dom;
local $body;
local %hash = ( 'USER' => $user,
		'FS' => $fs,
		'PERCENT' => int($percent),
		'USED' => $used,
		'QUOTA' => $limit );
if ($config{'email_msg'}) {
	# Use configured template
	$body = &substitute_template($config{'email_msg'}, \%hash);
	$body =~ s/\t/\n/g;
	}
else {
	# Fall back to default
	$body = &text('email_msg', $user, $fs, int($percent), $used, $limit);
	$body =~ s/\\n/\n/g;
	}
local $subject;
if ($config{'email_subject'}) {
	# Use configured subject
	$subject = &substitute_template($config{'email_subject'}, \%hash);
	}
else {
	# Fall back to default
	$subject = $text{'email_subject'};
	}
local $mail = { 'headers' => [ [ 'From', $from ||
					 'webmin@'.&get_system_hostname() ],
			       [ 'To', $addr ],
			       [ 'Subject', $subject ],
			     ],
		'attach' =>
			[ { 'headers' => [ [ 'Content-type', 'text/plain' ] ],
			    'data' => $body } ]
	      };
&mailboxes::send_mail($mail);
}

