#!/usr/bin/perl
#
my $ADMIN_CONF = "/etc/vdr/plugins/admin/admin.conf";
my @ALL_PLG_LIB = `ls /usr/local/src/VDR/PLUGINS/lib/libvdr*.so* | sed -e "s/.*libvdr-//" | cut -f 1 -d "." |sort`;

my @ALL_PLG_INFO = `cat /etc/vdr/plugins/admin/plugins.info`;
my @INSTPLGS = `grep "PLG_[a-z0-9_\\-]*:[^0]" $ADMIN_CONF | cut -f 2,3 -d ":" |sort -n -k 2 -t ":" -r`;

my $SCR_NAME = "/etc/vdr/plugins/admin/cfgplg.pl";

my $tmp= `sed -i $ADMIN_CONF -e "/:PLG_*/d" -e "/^:Plugins/d"`;

open(ADMCONF, ">>$ADMIN_CONF") || die "$ADMIN_CONF kann nicht erstellt werden";

print ADMCONF ":Plugins\n";

my $INSTALLED_PLUGINS = "";

my %INST_PLG={};
my $num = 0;
if ( $#ARGV >= 0) {
   my $idx = 0;
   my $num = $#ARGV + 1;
   while ( $idx <= $#ARGV ) {
      if ( grep( /^$ARGV[$idx]$/, @ALL_PLG_LIB ) ) {
         $INST_PLG{ $ARGV[$idx] } = $num;
         my @plginfo = grep( /^$plugin /, @ALL_PLG_INFO );
         my $info = $ARGV[$idx]; 
         if ( $plginfo[0] ) {
            $info = substr( $plginfo[0], length( $ARGV[$idx] ) + 1 );
            chomp $info;
         }
         print ADMCONF "$SCR_NAME:PLG_$ARGV[$idx]:$num:I:0:0,999:$info:\n";
         $INSTALLED_PLUGINS = "$INSTALLED_PLUGINS $ARGV[$idx]";
      }
      else {
         print "Plugin: $ARGV[$idx] not found\n";
      }
      $num --;
      $idx ++;
   }
}
else {
   $num = $#INSTPLGS + 1;
   foreach $plg ( @INSTPLGS ) {
      chomp $plg;
      @plgs = split( /[_:]/, $plg );
      $INST_PLG{ $plgs[1] } = $num;
      my @plginfo = grep( /^$plgs[1] /, @ALL_PLG_INFO );
      my $info = $plgs[1];
      if ( $plginfo[0] ) {
         $info = substr( $plginfo[0], length( $plgs[1] ) + 1 );
         chomp $info;
      }
      print ADMCONF "$SCR_NAME:PLG_$plgs[1]:$num:I:0:0,999:$info:\n";
      $INSTALLED_PLUGINS = "$INSTALLED_PLUGINS $plgs[1]";
      $num --;
   }
}

foreach $plugin (@ALL_PLG_LIB) {
   chomp $plugin;
   my $plgnum = $INST_PLG{ $plugin };
   if ( (! $plgnum) || $plgnum == 0 ) {
      $plgnum = 0;
      my $info = $plugin; 
      my @plginfo = grep( /^$plugin /, @ALL_PLG_INFO );
      if ( $plginfo[0] ) {
         my $info = substr( $plginfo[0], length( $plugin ) + 1 );
         chomp $info;
      }
      print ADMCONF "$SCR_NAME:PLG_$plugin:0:I:0:0,999:$info:\n";
   }
}
close(ADMCONF);
system( "sed -i /etc/conf.d/vdr -e 's/^PLUGINS=.*/PLUGINS=\"$INSTALLED_PLUGINS\"/'" );
print "Installed plugins: $INSTALLED_PLUGINS\n";

exit 0
