#!/usr/bin/perl -w

package Tpop3d::Mailbox;

require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(
	create_mailbox
	delete_mailbox
	mailbox_size
);

use warnings;
use strict;
use File::Spec::Functions qw(catfile);

my $spool_root  = q[/var/mail];
my $mail_user   = q[mail];
my ($mail_uid,$mail_gid) = (getpwnam($mail_user))[2,3]
	or die "$0: [internal] $mail_user not in passwd file";

sub mailbox_spool_dir($$) {
	my ($local_part, $domain) = @_;

	my $spool_dir = catfile($spool_root, $domain);
	my $mailbox = catfile($spool_dir, $local_part);

	($mailbox, $spool_dir);
}

sub create_mailbox($$) {
	my ($mailbox, $spool_dir) = mailbox_spool_dir($_[0], $_[1]);

	unless (-d $spool_dir) {
		mkdir $spool_dir, 0775
			or die "Can't create spool directory '$spool_dir': $!\n";
		print "Created $spool_dir\n";
	}
	chown($mail_uid, $mail_gid, $spool_dir) == 1
		or die "Can't chown $mail_user spool directory '$spool_dir': $!\n";

	unless (-f $mailbox) {
		open M, '>', $mailbox or die "Can't create '$mailbox': $!\n";
		close M;
	}
	chown($mail_uid, $mail_gid => $mailbox) == 1
		or die "Can't chown $mail_user mailbox '$mailbox': $!\n";
	chmod 0660 => $mailbox
		or die "Can't chmod 0660 => mailbox '$mailbox': $!\n";
}

sub mailbox_size($$) {
	warn "mailbox_size: ", join(", ", @_), "\n";
	my ($mailbox, $spool_dir) = mailbox_spool_dir($_[0], $_[1]);
	-f $mailbox && -s _;
}

# Should delete_mailbox clear up the directory when no more mailboxen
# remain?

sub delete_mailbox($$) {
	my ($mailbox, $spool_dir) = mailbox_spool_dir($_[0], $_[1]);
	warn "DELETING $mailbox\n";
	unlink($mailbox) == 1;
}

1;

__END__

=head1 NAME

Tpop3d::Mailbox

=head1 SYNOPSIS

create_mailbox($local_part, $domain);
delete_mailbox($local_part, $domain);
mailbox_size($local_part, $domain);

=head1 DESCRIPTION

=over 4

=item * create_mailbox($local_part_domain)

=over 4

=item * Ensure the directory C</var/mail/$domain> exists and is owned
by C<mail>

=item * Create, if necessary, a zero-length mailbox file
C</var/mail/$domain/$local_part>, also owned by C<mail>.

=back 4

=item * delete_mailbox($local_part, $domain)

Remove the mailbox. Return success of unlinking.

=item * mailbox_size($local_part, $domain)

Report size in bytes of mailbox.

=back 4

These paths can be adjusted by modifying C<Tpop3d::Mailbox>.

=head1 BUGS

Bug reports and patches welcome.

=head1 SEE ALSO

L<Tpop3d::Passwd>, L<tpop3d>, L<tpop3d.conf>

=head1 AUTHOR

Copyright (C) 2002-3 Paul Makepeace <http://paulm.com/>

This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

=cut
