#!/usr/bin/perl -Tw
######################################################################
# regmp.pl
######################################################################
# Perl Power! - Michael Schilli 1998
######################################################################

use CGI qw/:standard :html3/;      # standard CGI functions
use Fcntl qw/:flock/;              # define LOCK_EX etc.

my $efile = 'email.dat';           # address file

if(! defined param('email')) {     # no email entered (first 
                                   # call?) => introductory page
    print_form("Please enter your email address.");

} elsif (param('email') =~ /\S\@.+?\..+/) {
                                   # valid email => store
    if(register_email(param('email'), $efile)) {
        print_form("Registration successful. Thank you.");
    } else {
        print_form("Error: $ERROR");
    }

} else {                           # nonsense entered; repeat 
                                   # with error message
    print_form("Invalid email address - please try again.");
}

######################################################################
sub print_form {               # output form together with message text
######################################################################
    my ($message) = @_;

    print header,
          start_html('-title' => "Registration"),
          h2($message), start_form(), 
          table(TR(td("Email:"),
                   td(textfield(-name => 'email', 
                                -value => (param('email') || ""))),
                   td(submit(-value => "Register")))),
          end_form();
}

######################################################################
sub register_email {               # include email in file
######################################################################
    my ($email, $filename) = @_;
                                   # create file, if  
                                   # not yet existing
    do {open(FILE, ">$efile"); close(FILE)} unless -f $efile;

    if(!open(FILE, "+<$efile")) {  # open for read/write access
        $ERROR = "Cannot open $efile (internal error)."; 
        return 0;
    }

    flock(FILE, LOCK_EX);          # protect agaist parallel access
    seek(FILE, 0, 0);              # move to beginning of file

    while(<FILE>) {                # search for new email
        chomp;                     # strip newline
        if($_ eq $email) {
            $ERROR = "You are already registered.";
            close(FILE);
            return 0;
        }
    }
        
    seek(FILE, 0, 2);              # append email to end of file
    print FILE "$email\n";
    close(FILE);
    return 1;
}

