#!/usr/bin/perl

use strict;
use warnings;
#############################
# my modules
use Config::IniFiles;
use POSIX;
#############################
# Setting
my $config_dir = '/etc/asterisk';
my $lock_file = '/var/run/ast-ngrep.pid';
my $runas_user = 'asterisk';
my $nas_ip;


#############################
# Check if already running
if( -e $lock_file ) {
	open(PID,$lock_file);
	my $pid=<PID>;
	close PID;
	chomp $pid;
	if( !-e "/proc/$pid" ) {
		print STDERR "Lock file present, but no process with pid=$pid.\n";
		die "Can't delete lock file $lock_file\n" if !unlink $lock_file;
		print STDERR "Lock file has been removed.\n";
	} else {
		die "Lockfile present, another copy is punning pid=$pid\n";
	}
}
my ($name, $passwd, $uid, $gid) = getpwnam($runas_user) or die "$runas_user not in passwd file";;
#############################
# set C locale
POSIX::setlocale(LC_ALL, "C");
exit if !load_config();
#############################
# Become daemon
my $pid;
if( !defined($pid = fork()) ) 
	{
	die "cannot fork: $!";
	} 
elsif ($pid) 
	{
	# Create lockfile, and finish parent process
	open(PID, "> $lock_file") || die "ast-ngrep.pl: Unable to create lockfile $lock_file\n";
	print PID "$pid";
	close PID;
	chown $uid, $gid, $lock_file;
	exit;
	} 
	else 
		{
		# daemon
		setpgrp();
		select(STDERR); $| = 1;
		select(STDOUT); $| = 1;
		}


open COMMAND, '/usr/bin/ngrep -pql -W byline "" port 5060 |';
open LOG, ">/var/sipenv-$nas_ip/log/sip.log" || die ("Erreur d'ouverture du fichier /var/sipenv-*/log/sip.log") ;
my $LN;
while (<COMMAND>)
	{
	$LN=$_;
	chomp($LN);
	print LOG "\n$LN";
	}
#############################
# Load config from extensions.conf
sub load_config {
        my $conf=Config::IniFiles->new(-file => "$config_dir/extensions.conf");
	if (!defined $conf)
		{
		print STDERR "Config file error!\n";
		return 0;
		}
        $nas_ip = $conf->val('globals','NAS_IP_Address');
        print STDERR "$config_dir/extensions.conf loaded\n";
	return 1;
}

