#!/usr/bin/perl -wT

use strict;

use LWP::Simple;
use User::pwent;
use User::grent;
use Mail::Sendmail;

sub getmailbody($;$) {
	my $info = shift;
	my $lang = shift || 'en';

	my $baseurl = "http://support.kaospilot.no/";
	my $url = $baseurl . $info . "/email." . $lang . ".txt";

	my $mailbody = get($url) || die "Couldn't get email content from <$url>.";

	return ($mailbody);
}

sub getuserinfo($) {
	my $username = shift;

	my $pw = getpwnam($username) || die "Username \"$username\" does not exist.";

	my ($fullname, $office, $workphone, $homephone, $other) = split /\s*,\s*/, $pw->gecos;
	my @addresshints;
	if (defined($other)) {
		@addresshints = grep {/^([\.[:alnum:]_-]+|\+)?@([\.[:alnum:]_-]+)?$/} split /\s+/, $other;
	}

	return ($fullname, @addresshints);
}

my $mailbody = getmailbody("intro", "da");

while (my $username = shift @ARGV) {

	my ($fullname, @addresses) = getuserinfo($username);
	my $localaddress = "$username\@users.kaospilot.no";

	my %mail = (
		To		=> join(", ", grep {/^[\.[:alnum:]_-]+@[\.[:alnum:]_-]+\.[[:alnum:]_-]+$/} @addresses),
		Cc		=> $username . '@users.kaospilot.no',
		From		=> 'jonas@kaospilot.no',
		Bcc		=> 'hostmaster@kaospilot.no',
		'Reply-to'	=> 'tech@lists.kaospilot.no',
		Subject		=> "Din konto ved kaospilot.no",
		'Content-Type'	=> 'text/plain; charset="UTF-8"'
	);

	$mail{'body'} = $mailbody;
	$mail{'body'} =~ s/<fullname>/$fullname/g;
	$mail{'body'} =~ s/<username>/$username/g;
	$mail{'body'} =~ s/<addresses>/$localaddress/g;
	$mail{'body'} =~ s/<me>/Jonas Smedegaard/g;

	sendmail(%mail) or do {
		warn 'Error sending request: ' . $Mail::Sendmail::error;
	}
#DEBUG	warn "Request forwarded to Mailman. Log says:\n", $Mail::Sendmail::log;

}

__END__

my $valid_email = '/^[+_A-Za-z0-9-]+(\.[+_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[_A-Za-z0-9-]+)$/';

# Mail functions require this for tainted mode
$ENV{PATH} = '/tmp';

my ($from, $mailname, $action, $subject, $infostring, $errors);

warn $ARGV[0];