#!/usr/bin/perl -w

# send same message and different attachements to people. Run this script
# without arguments to see usage, and customize message on top of script
#
# Dobrica Pavlinusic, http://www.rot13.org/~dpavlin/sysadmin.html

use strict;
use MIME::Lite;

# customize this part !!
my $from = 'Joe Doe <joe.doe@nobody.com>';
my $subject = "New informations about...";
my $errors = 'postmaster@nobody.com';
my $body = "Please find attached more information about...";
# end of user configuration

my %ext2mime;

open(MIME,"/etc/mime.types") || die "mime.types: $!";
while(<MIME>) {
	chomp;
	next if (/^ *$/ || /^ *#/);
	my ($type,$exts) = split(/[ \t]+/,$_,2);
	if ($exts) {
		foreach my $ext (split(/[ \t]+/,$exts)) {
			$ext2mime{$ext} = $type;
		}
	}

}
close(MIME);

my $curr_dir = shift @ARGV;

if (! $curr_dir) {
	print "\nUsage: $0 [directory]\n\n";
	print "directory should containt directories which are valid e-mail\n";
	print "addresses (like first.last\@pliva.com) and attachements inside\n";
	print "that directory (directories without \@ will be ignored !!).\n";
	print "All files in selected directory will be ignored.\n\n";
	exit 1;
}

opendir(DIR, $curr_dir) || warn "can't opendir $curr_dir: $!";
my @dirs = grep { !/^\./ && -d "$curr_dir/$_" } readdir(DIR);
closedir(DIR);

print "Using dirs: ",join(", ",@dirs),"\n\n";

my @failed;

sub f {
	my $msg = shift;
	push @failed, $msg;
	print STDERR  "$msg\n";
}


my $max = $#dirs+1;
my $nr = 1;

foreach my $dir (@dirs) {

	if ($dir !~ m/\@/) {
		f("directory '$dir' don't have @ in name!");
		next;
	}

	if (! opendir(DIR, "$curr_dir/$dir")) {
		f("can't open '$dir': $!");
		next;
	}

	my @files = grep { !/^\./ && -f "$curr_dir/$dir/$_" } readdir(DIR);
	closedir(DIR);

	my $msg = new MIME::Lite(
		From    => $from,
		To      => $dir,
		Subject => $subject,
		Type    =>'multipart/mixed');

	$msg->add('Errors-To' => $errors);

	# debug
	$msg->add('X-To' => $dir);

	print STDERR "[$nr/$max] working on $dir...\n";
	$nr++;

	attach $msg (
		Type     => 'TEXT',
		Data     => $body
		);

	foreach my $file (@files) {

		my $type = 'application/octet-stream';

		if ($file =~ m/\.([^\.]+)$/) {
			$type = $ext2mime{$1} if ($ext2mime{$1});
		}

		print STDERR "\tadding '$file' ($type)\n";

		attach $msg (
			Type     => $type,
			Path     => "$curr_dir/$dir/$file",
			Filename => $file);

	}

	if (! $msg->send) {
		f("can't send e-mail to: $dir");
	}
}

if (@failed) {
	open(ERRORS,"> errors.log") || warn "can't open errors.log: $!";
	print "\nERRORS during this run (also saved in errors.log):\n";
	print join("\n",@failed);
	print ERRORS join("\n",@failed);
	print "\n";
	close(ERRORS);
}
