#!/usr/bin/perl
#
# You can use this script to add, delete, modify sip friends|peers|users
# Execution: ./sip_edit.pl <action> <username> <secret> <extension>
#            action = create|delete|edit 
#
# ./sip_edit.pl create test_user mysecret 123
#     this would create the following new record in sip_conf file using Defaults (see below)
#     [123]
#     username=test_user
#     secret=mysecret
#     callerid=123
#     type=friend
#     dtmf=RFC2833
#     nat=yes
#     context=sip_out
#     host=dynamic
#     externalauth=yes
#
# ./sip_edit.pl delete test_user secret 123
#    this would delete user 'test_user' from sip_conf
#
# ./sip_edit.pl edit test_user newsecret 123
#    you can edit ONLY username and secret, but not extension
#
#

use File::Copy;
use Asterisk::Manager;

my $sip_conf = '/etc/asterisk/sip.conf';
my $Defaults = 
'type=friend
dtmf=RFC2833
nat=yes
context=sip_out
host=dynamic
externalauth=yes
';

my $manager_user='test';
my $manager_pass='test';




my $action = shift;
my $user = shift;
my $pass = shift;
my $num = shift;


if (!(($action =~ /edit/i)||($action =~ /create/i)||($action =~ /delete/i))){
  die "Bad action '".$action."'";
}

if ( (! defined $num) || ($num eq 'NONE') ) {
  $num = $user;
}

my $out = '';
my $found = 0;
my $euser=0;
my $epass=0;
my $enum=0;

open(FD,$sip_conf);
while(<FD>){
  next if $_ =~ /^\s*$/;
  if ($_ =~ /^\s*\;.*/){
    $out = $out.$_;
    next;
  }
 # print $_;
  if ($_ =~ /^\[$num\]/){
    $found = 1;
    $out = $out.$_ if $action =~ /edit/i;
    next;
  }
  if ( $found && ($_ =~ /^\[.+\]/) ){
    $found = 0;
    if ($action =~ /edit/i){
      $out = $out.'username='.$user."\n" unless $euser;
      $out = $out.'secret='.$pass."\n" unless $epass;
      $out = $out.'callerid='.$num."\n" unless $enum;
      $out = $out.$_;
    }
    next;
  }
  if ( $found ) {
    if($_ =~ /username=.*/){
      $_="username=$user\n";
      $euser = 1;
    }
    if($_ =~ /secret=.*/){
      $_="secret=$pass\n";
      $epass = 1;
    }
    if($_ =~ /callerid=.*/){
      $_="callerid=$num\n";
      $enum = 1;
    }
    $out = $out.$_ if $action =~ /edit/i;
    next;
  }
  $out =$out.$_;
}

if ( $found && ($action =~ /edit/i) ){
  $out = $out.'username='.$user."\n" if ! $euser;
  $out = $out.'secret='.$pass."\n" if ! $epass;
  $out = $out.'callerid='.$num."\n" if ! $enum;
}

if ( ($action =~ /create/i) || (($action =~ /edit/i) && ! $found && ! $euser) ){
  $out = $out."[$num]\n";
  $out = $out.'username='.$user."\n";
  $out = $out.'secret='.$pass."\n";
  $out = $out.'callerid='.$num."\n";
  $out = $out.$Defaults;
}
close(FD);
copy($sip_conf, $sip_conf."\.bkp");

open(FD,">$sip_conf");
print FD "$out";
close(FD);

my $astman = new Asterisk::Manager;
$astman->user($manager_user);
$astman->secret($manager_pass);
$astman->host("127.0.0.1");
if( $astman->connect ) {
	$astman->command('sip reload');
} else {
		die "Can't connect to asterisk";
}
$astman->disconnect;

exit 0;
