#!/usr/bin/perl -w
#============================================================================#
#            Run PBX administration utilites from command line               #
#============================================================================#
# (C) Denis Smirnov <ds@seiros.ru>                               21 Nov 2008 #
#============================================================================#
use strict;

my $sudo = 0;
{
    my @user = getpwuid $<;
    $sudo = 1 if $< != 0 and $user[0] ne '_asterisk';
}

sub cmd_not_found($) {
    print STDERR "command '$_[0]' not found\n";
    exit(-1);
}

# Exec that more correct works in -T mode
sub myexec($@) {
    my $bin = shift;
    my @args;
    push @args, $bin;
    push @args, @_;
    delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
    $ENV{'PATH'} = '/bin:/usr/bin';
    exec {$bin} @args;
}

my $use = "Use: pbx <command> [<parameters> ..]
Or pbx -l for list of available commands
";

my $fn = $ARGV[0] || die "$use";

if ( $fn eq '-l' ) {
    foreach ( glob('/usr/libexec/pbx/*') ) {
        $_ =~ s/\.[^\.]*$//;
        $_ =~ s/^.*\///;
        print "$_\n";
    }
    exit 0;
}

# some security code
$fn =~ /([a-zA-Z0-9_-]+)/;
my $fnf = $1;
if ( $fnf ne $fn ) {
    print STDERR "invalid command: '$fn'\n";
    exit(-1);
}

my $cmd = "/usr/libexec/pbx/$fnf";

# find binary for this command
if ( !-x $cmd ) {

    # try to find other binary
    my @cmd = glob( $cmd . ".*" );
    cmd_not_found($fn) if @cmd != 1;
    $cmd[0] =~ /^([\/a-zA-Z0-9_\-\.]+)$/;
    cmd_not_found($fn) if $1 ne $cmd[0];
    $cmd = $1;
}

shift(@ARGV);

if ($sudo) {
    unshift( @ARGV, $cmd );
    unshift( @ARGV, "root" );
    unshift( @ARGV, "-u" );
    $cmd = '/usr/bin/sudo';
}
myexec( $cmd, @ARGV );
