#!/usr/bin/perl -Tw
#
#  LMS version 1.11.7 Bastet
#
#  Copyright (C) 2001-2009 LMS Developers
#
#  Please, see the doc/AUTHORS for more information about authors!
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License Version 2 as
#  published by the Free Software Foundation.
#
#  This program 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 this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
#  USA.
#
#  $Id: lms-reminder,v 1.21 2009/01/13 07:45:28 alec Exp $

use strict;
use DBI;
use Config::IniFiles;
use Getopt::Long;
use vars qw($configfile $quiet $help $version);
use POSIX qw(strftime mktime floor);
use MIME::QuotedPrint;
use Mail::Sender;

my $_version = '1.11.7 Bastet';

my %options = (
	"--config-file|C=s"	=>	\$configfile,
	"--quiet|q"		=>	\$quiet,
	"--help|h"		=>	\$help,
	"--version|v"		=>	\$version
);

Getopt::Long::config("no_ignore_case");
GetOptions(%options);

if($help)
{
	print STDERR <<EOF;
lms-reminder, version $_version
(C) 2001-2009 LMS Developers

-C, --config-file=/etc/lms/lms.ini	alternate config file (default: /etc/lms/lms.ini);
-h, --help			print this help and exit;
-v, --version			print version info and exit;
-q, --quiet			suppress any output, except errors;

EOF
	exit 0;
}

if($version)
{
	print STDERR <<EOF;
lms-reminder, version $_version
(C) 2001-2009 LMS Developers

EOF
	exit 0;
}

if(!$configfile)
{
	$configfile = "/etc/lms/lms.ini";
}

if(!$quiet)
{
	print STDOUT "lms-reminder, version $_version\n";
	print STDOUT "(C) 2001-2009 LMS Developers\n";
	print STDOUT "Using file $configfile as config.\n";
}

if(! -r $configfile)
{
	print STDERR "Fatal error: Unable to read configuration file $configfile, exiting.\n";
	exit 1;
}

my $ini = new Config::IniFiles -file => $configfile;
print @Config::IniFiles::errors;

my $dbtype = $ini->val('database', 'type') || 'mysql';
my $dbhost = $ini->val('database', 'host') || 'localhost';
my $dbuser = $ini->val('database', 'user') || 'root';
my $dbpasswd = $ini->val('database', 'password') || '';
my $dbname = $ini->val('database', 'database') || 'lms';

my $mailfrom = $ini->val('reminder', 'mailfrom') || '';
my $mailfname = $ini->val('reminder', 'mailfname') || '';
my $mailsubject = $ini->val('reminder', 'mailsubject') || '';
my $debugemail = $ini->val('reminder', 'debug_email') || '';

my $smtp_host = $ini->val('reminder', 'smtp_host') || 'localhost';
my $smtp_user = $ini->val('reminder', 'smtp_user') || '';
my $smtp_pass = $ini->val('reminder', 'smtp_pass') || '';
my $smtp_auth = $ini->val('reminder', 'smtp_auth') || ''; # 'LOGIN', 'PLAIN', 'CRAM-MD5', 'NTLM'

if(!$mailfrom)
{
	print STDERR "Fatal error: mailfrom unset! Can't continue, exiting.\n";
	exit 1;
}

if(!$mailfname)
{
	print STDERR "Fatal error: mailfname unset! Can't continue, exiting.\n";
	exit 1;
}

if(!$mailsubject)
{
	print STDERR "Fatal error: mailsubject unset! Can't continue, exiting.\n";
	exit 1;
}

if($smtp_auth && $smtp_auth !~ /LOGIN|PLAIN|CRAM-MD5|NTLM/i)
{
        print STDERR "Fatal error: smtp_auth setting not supported! Can't continue, exiting.\n";
        exit 1;
}

my $dbase;
		
if($dbtype =~ /mysql/)
{
	$dbase = DBI->connect("DBI:mysql:database=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
	$dbase->do("SET NAMES utf8");
}
elsif($dbtype eq "postgres")
{
	$dbase = DBI->connect("DBI:Pg:dbname=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
}
else
{
	print STDERR "Fatal error: unsupported database type: $dbtype, exiting.\n";
	exit 1;
}

$Mail::Sender::NO_X_MAILER = 1;
$Mail::Sender::SITE_HEADERS = "X-Mailer: lms-reminder v.$_version";

my $date = mktime(0, 0, 0, strftime("%e",localtime()), strftime("%m",localtime())-1, strftime("%Y",localtime())-1900, 0, 0, -1);
my $day = strftime("%x", 0, 0, 0, strftime("%e",localtime()), strftime("%m",localtime())-1, strftime("%Y",localtime())-1900, 0, 0, -1);

my $dbq = $dbase->prepare("SELECT id, name, email FROM users WHERE deleted = 0 AND email != ''");
$dbq->execute();
while (my $row = $dbq->fetchrow_hashref())
{
	my $counter = 0;
	my $contents = '';
	my $recipient = $row->{'email'};
	
	my $dbqi = $dbase->prepare("SELECT DISTINCT title, description, begintime, endtime,
			customerid, UPPER(lastname) AS lastname, customers.name AS name, address, city, zip,
			(SELECT phone FROM customercontacts 
				WHERE customerid = events.customerid 
				ORDER BY phone LIMIT 1) AS phone 
			FROM events 
			LEFT JOIN customers ON (customers.id = customerid)
			LEFT JOIN eventassignments ON (events.id = eventid)
			WHERE date=$date AND
			((private=1 AND events.userid=$row->{'id'}) OR
			(private=0 AND eventassignments.userid=$row->{'id'}) OR
			(private=0 AND eventassignments.userid IS NULL))
			ORDER BY begintime");
	$dbqi->execute();
 	while (my $rowi = $dbqi->fetchrow_hashref())
	{
		my $begintime = sprintf("%02d:%02d",floor($rowi->{'begintime'}/100),$rowi->{'begintime'}%100);

		$contents .= "Timetable for today ($day)\n";
		$contents .= "----------------------------------------------------------------------------\n";
		$contents .= "Time :\t$begintime";
		if($rowi->{'endtime'} && $rowi->{'endtime'} != $rowi->{'begintime'})
		{
			my $endtime = sprintf("%02d:%02d",floor($rowi->{'endtime'}/100),$rowi->{'endtime'}%100);
			$contents .= " - $endtime";
		}
		$contents .= "\n";
		
		$contents .= "Title:\t$rowi->{'title'}\n";

		$contents .= "Desc.:\t$rowi->{'description'}\n";

		if($rowi->{'customerid'})
		{
			$contents .= "Cust.:\t$rowi->{'lastname'} $rowi->{'name'}, $rowi->{'zip'} $rowi->{'city'}, $rowi->{'address'}, $rowi->{'phone'}\n";
		}

		$contents .= "----------------------------------------------------------------------------\n";
		$counter++;
	}
	
	if($counter)
	{
		if(!$quiet)
		{
			print STDOUT "$row->{'name'} ($row->{'id'}) - $counter event(s)\n";
		}

		if($debugemail)
		{
			$recipient = $debugemail;
		}

		(new Mail::Sender)->MailMsg ({
                	smtp => $smtp_host,
		        from => $mailfrom,
			auth => $smtp_auth,
			authid => $smtp_user,
			authpwd => $smtp_pass,
			on_errors => undef,
			#debug_level => 4,
			#debug => './log.txt',
			subject => '=?UTF-8?Q?'.encode_qp($mailsubject, '').'?=',
			fake_from => $mailfname || $mailfrom,
			to => $recipient,
			fake_to => '"=?UTF-8?Q?'.encode_qp($row->{'name'}).'?="'.' <'.$recipient.'>',
			replyto => $mailfrom,
			ctype => 'text/plain',
			encoding => '8bit',
			charset => 'UTF-8',
			msg => "$contents\n",
		}) or print STDERR "Error sending mail: $Mail::Sender::Error\n";
	}
}

$dbq->finish();
$dbase->disconnect();
