#!/usr/bin/perl

=head1 NAME

Send-reminders - send email reminders for special occasions

=head1 SYNOPSIS

Send emails reminders set by users for special occasions.

=head1 DESCRIPTION

Email-reminder allows users to define events that they want to be
reminded of by email.  Possible events include birthdays,
anniversaries and yearly events.  Reminders can be sent on the day of
the event and a few days beforehand.

This script is meant to be invoked everyday by a cron job.  It mails
the actual reminders out.

When run by the root user, it processes reminders for all users.  When
run by a specific user, it only processes reminders set by that user.

=head1 OPTIONS

=over 6

=item B<--help>

Displays basic usage message.

=item B<--simulate>

Does not actually send any emails out.

=item B<--verbose>

Prints out information about what the program is doing, including the
full emails being sent out.

=item B<--version>

Displays the version number.

=back

=head1 FILES

F<~/.email-reminders>, F</etc/email-reminder.conf>

=head1 AUTHOR

Francois Marier <francois@debian.org>

=head1 SEE ALSO

email-reminder-editor

=head1 COPYRIGHT

Copyright (C) 2004-2005 by Francois Marier

Email-Reminder is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.

Email-Reminder is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with Email-Reminder; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA

=cut

use strict;
use warnings;

use Getopt::Long;
use Net::SMTP;
use Pod::Usage;

use EmailReminder::EventList;
use EmailReminder::Utils;

# Default preferences
my $PREFERENCE_FILE = '/etc/email-reminder';
my %preferences;
$preferences{"send_reminders"}   = 1;
$preferences{"smtp_server"}      = 'localhost';
$preferences{"mail_from"}        = 'root@localhost';
read_config(); 

# Global variables
my $user_fname;
my $user_lname;

# Command-line parameters
my $verbose  = 0;
my $simulate = 0;
my $version  = 0;
my $help  = 0;
GetOptions( "verbose"  => \$verbose,
            "simulate" => \$simulate,
	    "version"  => \$version,
	    "help"     => \$help,
	    );

# Override preferences with system values
sub read_config
{
    if (open CONFIG, $PREFERENCE_FILE)
    {
	print "Reading preferences from '$PREFERENCE_FILE'\n" if $verbose;

	# Stolen off of the Cookbook (section 8.16)
	while (<CONFIG>) {
	    chomp;                  # no newline
	    s/#.*//;                # no comments
	    s/^\s+//;               # no leading white
	    s/\s+$//;               # no trailing white
	    next unless length;     # anything left?
	    my ($var, $value) = split(/\s*=\s*/, $_, 2);
	    $preferences{$var} = $value;
	}
	
	close CONFIG;
    }
}

sub send_email
{
    my $uid = shift;
    my $message = shift;
    my $user_name = shift;
    my $user_email = shift;

    unless ($user_email) {
        print "Cannot send email to $user_fname $user_lname:  email address not set.\n" if $verbose || $uid;
        return 0;
    }

    my $to = $user_email;
    $to = "$user_name <$user_email>" if defined($user_name);

    print "--> Emailing '$to':\n$message" if $verbose;
    
    unless ($simulate)
    {
	my $smtp = Net::SMTP->new($preferences{"smtp_server"}, Debug => 0);
	die "Couldn't connect to server" unless $smtp;

	$smtp->mail($preferences{"mail_from"});
	$smtp->to($to);

	$smtp->data();
	$smtp->datasend("From: Email-Reminder <" .
			$preferences{"mail_from"} . ">\n");
	$smtp->datasend("To: $to\n");
	$smtp->datasend("$message");
	$smtp->dataend();

	$smtp->quit();
    }

    return 1;
}

sub process_homedir
{
    my $uid = shift;
    my $homedir = shift;

    my $file = "$homedir/" . $EmailReminder::Utils::USER_CONFIG_FILE;
    if (-e $file)
    {
        print "==> Processing $file\n" if $verbose;

        my $list = EmailReminder::EventList->new($file);
        
	my @fullname = $list->get_user_name();
        my $user_fname = $fullname[0];
        my $user_lname = $fullname[1];
	my $user_name = $user_fname;
	$user_name .= " " . $user_lname if defined($user_lname);
	my $user_email = $list->get_user_email();
        
        foreach my $event ($list->get_events())
        {
            if ($event->is_occurring())
            {
                my $msg = $event->get_message($user_fname);
		my $reminder_email = $event->get_reminder_email();
		my $reminder_name = $event->get_reminder_name();
		
		my $recipient_name = defined($reminder_name) ? $reminder_name : $user_name;
		my $recipient_address = defined($reminder_email) ? $reminder_email : $user_email;

                my $success = send_email($uid, $msg, $recipient_name, $recipient_address) if $msg;
                return 0 if !$success;
            }
        }

        return 1;
    }

    return 0;
}

sub main
{
    my $running_uid = $>;
    if ($running_uid == 0) {
        # Iterate through all local users when root
        while (my ($name, undef, $uid, undef, undef, undef, undef, 
                   $homedir, $shell, undef) = getpwent) 
        {
            # Try to skip non-human users
            if (($uid > 100) && ($uid < 60000) && ($shell ne '/bin/false')) {
                process_homedir($running_uid, $homedir);
            }
        }
    } else {
        # Normal users only get to test their own reminders
        my @pwinfo = getpwuid($>);
        process_homedir($running_uid, $pwinfo[7]);
    }
}

if ($help || $version) {
    print "send-reminders $EmailReminder::Utils::VERSION\n";
    if ($help) {
	print "\n";
	pod2usage(1);
    } else {
	exit(1);
    }
} else {
    main() if $preferences{"send_reminders"};
}
