#!/usr/local/bin/perl -w
# $Id: ip-saver.pl,v 1.2 2000/08/25 11:02:07 mas Exp $
#
#    ip-saver.pl: CGI script to record IP addresses for handles.
#    Copyright 2000 Marc André Selig.
#
#    This program 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.
#
#    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., 675 Mass Ave, Cambridge, MA 02139, USA.

use strict;
use CGI;
use CGI::Carp;

my $db = "/tmp/ip-saver";
my %ips = ();
my %keys = ();
my $notice = undef;

if (open IN, $db) {
    while (<IN>) {
	chomp;
	my @F = split;
	$keys{$F[0]} = $F[1];
	$ips{$F[0]} = $F[2];
    }
    close IN;
}

my $q = new CGI;

if (defined $q->param('handle') and
    defined $q->param('getit')) {
    print "Content-Type: text/plain\n\n";
    if (defined $ips{$q->param('handle')} and
	$ips{$q->param('handle')} ne 'off') {
	print "$ips{$q->param('handle')}\n";
    } else {
	print "NOT LOGGED IN\n";
    }
    exit;
}

if (defined $q->param('handle')) {
    my $handle = $q->param('handle');

    if (not defined $keys{$handle}) {
	if (defined $q->param('key') and
	    $q->param('key') ne '') {
	    $keys{$handle} = $q->param('key');
	} else {
	    $keys{$handle} = int(rand 10000000);
	}
	$notice = "Your key is $keys{$handle}.  Please use this in future.";
	$ips{$handle} = $q->remote_host();
    } elsif (not defined $q->param('key') or
	     $q->param('key') ne $keys{$handle}) {
	$notice = "Authorization failed.";
    } else {			# handle/key pair is valid
	if (defined $q->param('off') and
	    $q->param('off') eq 'on') {
	    $ips{$handle} = 'off';
	} else {
	    $ips{$handle} = $q->remote_host();
	}
    }
}

print
    $q->header,
    $q->start_html('IP Saver'),
    $q->h1('IP Saver'), $q->hr,
    "<table border>\n",
    " <tr><th>Handle</th><th>Host</th></tr>\n";
foreach my $i (sort keys %ips) {
    print " <tr><td>$i</td><td>$ips{$i}</td></tr>\n" unless $ips{$i} eq 'off';
}
print "</table>\n";

print $q->p($notice) . "\n" if defined $notice;

print
    $q->startform(-method=>'POST'),
    $q->p("Handle: " .
	  $q->textfield(-name=>'handle',
			-size=>12,
			-maxlength=>12) .
	  "\nKey: " .
	  $q->textfield(-name=>'key',
			-size=>12,
			-maxlength=>12) .
	  "\n" .
	  $q->checkbox(-name=>'off') .
	  $q->submit("Absenden")),
    "\n", $q->endform, $q->hr, "\n";

open OUT, ">$db" or die "Cannot write to $db: $!";
foreach my $handle (keys %ips) {
    print OUT "$handle\t$keys{$handle}\t$ips{$handle}\n";
}
close OUT;

