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

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

# read /etc/conf.d/vdr into hash %VC
open(VDRCONF, "<$VDR_CONF") || die "$VDR_CONF nicht gefunden";
my @Lines = <VDRCONF>;
close(VDRCONF);
my %VC={};
#my @NeueZeilen;
foreach $line (@Lines) {
  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";
}

# Now rewrite admin.conf
open(ADMCONF, "<$ADMIN_CFGFILE") || die "$ADMIN_CFGFILE nicht gefunden";
my @Lines = <ADMCONF>;
close(ADMCONF);

unlink( "$ADMIN_CFGFILE.save");
move( $ADMIN_CFGFILE, "$ADMIN_CFGFILE.save");

if (!open(ADMCONF, ">$ADMIN_CFGFILE")) {
   move( "$ADMIN_CFGFILE.save", $ADMIN_CFGFILE);
   die "$ADMIN_CFGFILE kann nicht erstellt werden";
}

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

     if ($vars[1] && ($vars[1] !~ /^PLG_.*/) && ($vars[1] !~ /^UPD_.*/) ) {
        my $newval = $VC{$vars[1]};
        if (length($newval) > 0) {
           my $oldval = $vars[2];
           if ($vars[3] =~ /L/ ) {
              my @vals = split /,/, $vars[5];
              my $i = 0;
              my $found = 0;
              foreach $val (@vals) {
                 if ($val =~ /$newval/) {
                    $found = 1;
                    last;
                 }
                 $i++;
              }
              if (($found == 1) && ($i != $vars[2])) {
   #              print "$vars[1]-$vv-$vals[$vars[2]]-$i-$vars[2]\n";
                 $newval = $i;
              }
              else {
                 $newval = $oldval;
              }
           }
           if ($newval != $oldval) {
   #            print "$vars[1]-$newval-$oldval\n";
              $newline = "$vars[0]:$vars[1]:$newval:$vars[3]:$vars[4]:$vars[5]:$vars[6]:";
              print "$newline\n";
           }
        }
     }
  }

  if ($newline) {
     print ADMCONF "$newline\n"; 
  }

#  print "<$words[0]><$words[1]><$words[2]><$words[3]>\n";
}
close(ADMCONF);

# set the plugins
my $tmp= `perl /etc/vdr/plugins/admin/cfgplg.pl $VC{"PLUGINS"}`;

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


exit;

