#!/usr/bin/perl

# Forward email to all of the AREA game contacts in the database
# Bruno Wolff III
# Last updated May 14, 2002

# This program depends on qmail semantics for program delivery.
# It should be called using preline -r -f to add a delivered-to header
# to catch mail loops.

$" = '';

# Postgres perl library
use Pg;

# Path to qmail-inject binary
$qmail = '/var/qmail/bin/qmail-inject';

# Shut off STDERR so Pg doesn't write to it
close(STDERR);
open(STDERR, '>/dev/null');

# Connect to the AREA database

$conn = Pg::connectdb('dbname=area');
# Give a temporary failure if the database is unreachable
exit(111) if $conn->status != PGRES_CONNECTION_OK;

# Get recipient address and quote it
$rec = $ENV{RECIPIENT};
$rec =~ s/\\|'/\\$&/g;

# This program shouldn't send stuff to its own address.
$result = $conn->exec("select distinct email from contacts where lower(email) <> lower('$rec')");
if ($result->resultStatus != PGRES_TUPLES_OK) {
# Something is wrong with the database
  exit(111);
}

if ($result->ntuples <= 0) {
# No addresses, forward to AREA
  exec($qmail, "-f$ENV{SENDER}", 'area@kww.us');

# The forward failed
  exit(111);
}

@add = ();
while (@row = $result->fetchrow) {
  if (defined $row[0] && $row[0] ne '') {
    push @add, $row[0];
  }
}

if (scalar(@add) > 0) {
# forward to contact addresses
  exec($qmail, "-f$ENV{SENDER}", @add);
}
else {
# If we get here there was either a weird failure or the database structure
# changed to allow null email addresses and that was all that was returned.
# It is safer to send this on to the default address rather than return
# a temporary failure as it might be a relatively permanent failure.
  exec($qmail, "-f$ENV{SENDER}", 'area@kww.us');
}

# If we get here the exec statements failed for some reason. Lets hope
# that whatever was wrong gets fixed.
exit(111);
