#!/usr/bin/perl

# $Id: sequence-server.pl,v 1.1 2004/06/17 11:22:45 mike Exp $

use strict;
use warnings;
use Getopt::Std;
use IO::Socket::INET;

my %opts = ( p => 9000, f => "seqfile", s => 0 );
if (!getopts("p:f:n:", \%opts) || @ARGV > 0) {
    die "Usage: $0 [options]
	-p <n>	Listen on local port number <n> [default 9000]
	-f <x>	Load/save sequence number in file <x> [default seqfile]
	-s <n>	Start couinting from <n> if file doesn't exist [default 0]
";
}

my $port = $opts{p};
my $seqfile = $opts{f};
my $seq = $opts{s};		# will be overwritten if file exists
open F, "<$seqfile"
    or die "can't read from '$seqfile': $!" if $! != 2;
$seq = <F>;
close F;

my $listener = new IO::Socket::INET(Listen => 3,
				    Proto => "tcp",
				    LocalPort => $port,
				    ReuseAddr => 1)
    or die "can't create listening socket on port $port: $!";

$SIG{TERM} = \&save;

while (my $client = $listener->accept()) {
    $seq++;
    print $client "$seq\n";
    $client->close();
}

sub save {
    my($sig) = @_;

    print "$0: signal $sig: saving $seq to '$seqfile'\n";
    open F, ">$seqfile" or die "can't write to '$seqfile': $!";
    print F $seq;
    close F or die "can't close '$seqfile': $!";
}
