#!/usr/bin/perl
use File::Copy;

my $VDR_CONF = "/etc/conf.d/vdr";
my $ADMIN_CONF = "/etc/vdr/plugins/admin/admin.conf";

# read /etc/conf.d/vdr into hash %vc
open(VDRCONF, "<$VDR_CONF") || die "$VDR_CONF nicht gefunden";
my @vdrconf = <VDRCONF>;
close(VDRCONF);
my %vc;
#my @NeueZeilen;
foreach $line (@vdrconf) {
  chomp $line;
  my @vars = split /[# ="]/, $line;

  if ($vars[0]) {
     my @vals = split /"/, $line;
     $vc{$vars[0]}=$vals[1];
  }
#  print "<$words[0]><$words[1]><$words[2]><$words[3]>\n";
}

my %plugins;

# Now read admin.conf
open(ADMCONF, "<$ADMIN_CONF") || die "$ADMIN_CONF nicht gefunden";
my @admconf = <ADMCONF>;
close(ADMCONF);

#my @NeueZeilen;
foreach $line (@admconf) {
  chomp $line;
  my $newline = $line;
  if (index($line, "/") == 0) {
     my @vars = split /:/, $line;

     if ($vars[1] && ($vars[1] !~ /^PLG_.*/) && ($vars[1] !~ /^UPD_.*/) ) {
        my $val = $vars[2];
        if ($vars[3] =~ /L/ ) {
           my @vals = split /,/, $vars[5];
           $val = $vals[$vars[2]];
        }
        if ("$val" ne "$vc{$vars[1]}" ) {
           print "$vars[1] : <$val> != <$vc{$vars[1]}>\n";
           SetVal( $vars[1], $val );
        }
     }
     else {
        if ($vars[1] =~ /^PLG_.*/ && $vars[2] > 0) {
           $plugins{substr($vars[1],4)}=$vars[2];
        }
     }
  }
}
my $inst_plg = "";
foreach $key (sort hashPlgSort (keys(%plugins))) {
   $inst_plg = "$inst_plg $key";
}
print "Plugins <$inst_plg>\n";
SetVal( "PLUGINS", $inst_plg );


# read /etc/conf.d/vdr into hash %vc
unlink( "$VDR_CONF.save" );
rename( "$VDR_CONF", "$VDR_CONF.save" );
open(VDRCONF, ">$VDR_CONF") || die "$VDR_CONF nicht beschreibbar";
foreach $line (@vdrconf) {
   print VDRCONF "$line\n";
}
close(VDRCONF);

# set the plugins
#my $tmp= `perl /etc/vdr/plugins/admin/cfgplg.pl`;

# set the update
#my $tmp= `sh /etc/vdr/plugins/admin/cfgupd.sh`;


exit;

sub SetVal
{
   my $var = shift;
   my $val = shift;
   my $found = 0;
   
   # delete leading and trailing blanks
   $var =~ s/^\s+//;
   $var =~ s/\s+$//;
   $val =~ s/^\s+//;
   $val =~ s/\s+$//;
   
   foreach $line (@vdrconf) {
      if ( $line =~ /^$var[ =]/ ) {
         $line = "$var=\"$val\"";
         $found = 1;
      }
   }
   if ( ! $found ) {
      push( @vdrconf, "$var=\"$val\"" );
   }
}

sub hashPlgSort
{
   $plugins{$b} <=> $plugins{$a};
}
