#!/usr/bin/perl -w

print "reading channels.conf\n";
open (CHANNELS, "</video/channels.conf") || die "Can't open /video/channels.conf";

while (<CHANNELS>) {
    next if ($_ =~ /^:/ );
    $_ =~ /(.+):.+:.+:.+:.+:.+:.+:.+:(.+):.+:.+:.+:.+/;
    $name = $1;
    $ca = $2;
    if ($name =~ /.+;(.+)/) {
      $provider = $1;
      }
    if ($ca eq "0"){  
      #print "OpenProvider $provider  Ca: $ca\n";
      $openProvider{uc($provider)}=1;
    } else {
      @cas = split(/,/, $ca);
      #print "ClosedProvider $provider  Ca's:";
      $closedProvider{uc($provider)}=1;
      foreach $value (@cas) {
        #print "-$value ";
	$closedCa{uc($value)}=1;
	}
      #print"\n";
      }
    }
close (CHANNELS);

print "writing opengroups.conf.template1\n";
open (GROUPS, ">/video/plugins/autosort/opengroups.conf.template1") || die "Can't write /video/plugins/autosort/opengroups.conf.template1";
print GROUPS "\n#CA values you own a CAM for\n";
print GROUPS "\n#CA values you don't own a CAM for\n";
foreach $key (keys %closedCa){
    push(@list, $key);
    }
@lines = sort @list;
foreach $line (@lines){    
    print GROUPS "ClosedCa=$line:\n";
    }

print GROUPS "\n#Provider you have or don't need a card for\n";
@list=();
oP:foreach $key (keys %openProvider){
    foreach $key2 (keys %closedProvider){
      next oP if ($key eq $key2);  
      }
    push(@list, $key);
    }
@lines = sort @list;
foreach $line (@lines){    
    print GROUPS "OpenProvider=$line:\n";
    }

print GROUPS "\n#Provider you don't have a card for\n";
@list=();
foreach $key (keys %closedProvider){
    push(@list, $key);
    }
@lines = sort @list;
foreach $line (@lines){    
    print GROUPS "ClosedProvider=$line:\n";
    }
close (GROUPS);
print"template1 written\n";

print "writing opengroups.conf.template2\n";
open (GROUPS, ">/video/plugins/autosort/opengroups.conf.template2") || die "Can't write /video/plugins/autosort/opengroups.conf.template2";

print GROUPS "\n# ---- Known CA-values ----\n";
@list=();
foreach $key (keys %closedCa){
    push(@list, $key);
    }
@lines = sort @list;
foreach $line (@lines){    
    print GROUPS "ClosedCa =$line:\n";
    }

print GROUPS "\n# ---- Known Provider ----\n";

foreach $key (keys %openProvider){
    $Provider{$key} = 1;
    }

foreach $key (keys %closedProvider){
    $Provider{$key} = 2;
    }

@list=();
foreach $key (keys %Provider){
    push(@list, $key);
    }
@lines = sort @list;
foreach $line (@lines){
    if ($Provider{$line} == 1){
      print GROUPS "OpenProvider   =$line:\n";
    } else {
      print GROUPS "ClosedProvider =$line:\n";
      }
    }
close (GROUPS);
print"template2 written\n";
print"ready\n";
