#!/usr/bin/perl -w
##################################################
# Perl-Script zum rotierenden Ausliefern von
# Werbe-Bildern und -Links
# 1998, schilli@perlmeister.com
##################################################

use CGI qw(:standard);
                     # Send errors to Browser
use CGI::Carp 'fatalsToBrowser';

                     # Ad banner sequence file
$BANNER_SEQ_FILE   = "adserver.seq";
                     # Persistent counter
$BANNER_COUNT_FILE = "adserver.cnt";

                     # Open banner sequence file
open(SEQ, "<$BANNER_SEQ_FILE") || 
    die "Cannot open $BANNER_SEQ_FILE";

while(<SEQ>) {       # Read it and fill @banners
    chomp;           # Remove Newlines
    s/^\s*#.*//g;    # Remove comments
    next if /^\s*$/; # Ignore blank lines
                     # Extract two fields
    my ($img, $url) = split(' ', $_);
                     # Two fields, really?
    die "Invalid line in $BANNER_SEQ_FILE: $_" 
        unless defined $url;
    push(@banners, [$img, $url]);
}

close(SEQ);

    # Get and increase persistent counter
my $counter = (inc_counter() % ($#banners + 1));

    # Spit out CGI header and anchored image
print header(),
      a({href => $banners[$counter]->[1] }, 
        img({src => $banners[$counter]->[0]}));


##################################################
sub inc_counter {    # Get and increase 
                     # permanent counter
##################################################
    my $counter = 0;

            # Counter file exists?
    if(-f $BANNER_COUNT_FILE) {

            # Open it exclusively
        open(COUNT, "+<$BANNER_COUNT_FILE") || 
            die "Cannot r/w $BANNER_COUNT_FILE";

            # Lock it
        flock(COUNT, 2);

            # Read out value
        seek(COUNT, 0, 0);
        $counter = <COUNT>;
        chomp($counter);

            # Truncate file

        seek(COUNT, 0, 0);
        truncate(COUNT, 0);

    } else {
            # File doesn't exist - create it
        open(COUNT, ">$BANNER_COUNT_FILE") || 
            die "Cannot init $BANNER_COUNT_FILE";
    }

        # Write new value to counter file
    print COUNT $counter+1, "\n";

        # Close, implicitly release lock
    close(COUNT);

        # Return old counter value
    return $counter;
}
