#!%%PERL%% -w
#
use Sys::Syslog;
Sys::Syslog::setlogsock('unix');
use IPC::SysV qw(IPC_CREAT);
use IPC::SysV qw(IPC_NOWAIT);
use IPC::SysV qw(IPC_PRIVATE);
use IPC::SysV qw(IPC_RMID);


use lib "%%LIBEXECDIR%%";

use Nfcomm;

our $semlock;

sub semwait {
    my $sem=shift;
    semop($sem, pack("s3", 0, -1, 0)) || warn "semopt(): $!\n";
} # End of semwait

sub semnowait {
    my $sem=shift;
    return semop($sem, pack("s3", 0, -1, IPC_NOWAIT));
} # End of semnowait

sub semsignal {
    my $sem=shift;
    semop($sem, pack("s3", 0, +1, 0)) || warn "semopt(): $!\n";
} # End of semsignal


if ( !NfConf::LoadConfig() ) {
	die "$Log::ERROR\n";
}

Log::LogInit();
tie(*STDERR, 'Log', 'nfcomm');
print STDERR "Standalone comm server startup";

$semlock = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT ) || die "Can not get semaphore: $!";
semsignal($semlock);

print "Run standalone Comm Server:\n";
my $server = Nfcomm::Setup_Server('nfsen-current (comm)');
if ( !defined $server ) {
	die "Setup failed: $!\n";
}

Nfcomm::LoadPlugins();
Nfcomm::RunServer($server);
Nfcomm::Close_server($server);

# cleanup
semctl($semlock, 0, &IPC_RMID, 0);

untie *STDERR;
Log::LogEnd;

