#!/usr/bin/perl -Tw
#
#  LMS version 1.10.2 Roham
#
#  Copyright (C) 2001-2007 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.17.2.1 2007/08/17 13:14:49 alec Exp $

use strict;
use DBI;
use Config::IniFiles;
use Getopt::Long;
use Net::SMTP;
use vars qw($configfile $quiet $help $version);
use POSIX qw(strftime mktime floor);

my $_version = '1.10.2 Roham';

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-2007 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-2007 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-2007 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 $smtpserver = $ini->val('reminder', 'smtp_server') || '127.0.0.1';
my $debugemail = $ini->val('reminder', 'debug_email') || '';

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;
}

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;
}

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 $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 .= "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";
		}
	
		my $smtp = Net::SMTP->new("$smtpserver");
		$smtp->mail("$mailfrom");

		if($debugemail)
		{
			$smtp->to($debugemail);
		}
		else
		{
			$smtp->to($row->{'email'});
		}

		$smtp->data();

		$smtp->datasend("From: $mailfname <$mailfrom>\n");
		$smtp->datasend("To: $row->{'name'} <$row->{'email'}>\n");
		$smtp->datasend("Subject: $mailsubject\n");
    		$smtp->datasend("User-Agent: lms\-reminder v. $_version\n");
		$smtp->datasend("Content-type: text/plain; charset=UTF-8\n");
		$smtp->datasend("Mime-Version: 1.0\n");
		$smtp->datasend("Content-transfer-encoding: 8bit\n");
		$smtp->datasend("\n");
		$smtp->datasend("Timetable for today ($day)\n");
		$smtp->datasend("----------------------------------------------------------------------------\n");
 		$smtp->datasend("$contents\n");
		$smtp->dataend();
		$smtp->quit;
	}
}

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