
use strict;

print "Reading...\n";
open OLD, "pollustop.settings" or die "can't read settings file";
my @lines = <OLD>;
close OLD;
print "Backuping to pollustop.settings.old...\n";
open OLD, ">pollustop.settings.old" or die "can't write backup file";
print OLD join("", @lines);
close OLD;
print "Writing new settings file...\n";
my $cursec = "";
my %data = ();
foreach my $line (@lines)
{
   chomp $line;
   next if ($line =~ /^\s*#/);
   next if ($line =~ /^\s*$/);
   if ($line =~ /^((GENERAL)|(FILTER)|(LEARN)|(LOG)|(MATHS)|(DROPMAILBOXES))/i)
   {
      $cursec = lc($line);
      $cursec = "m" if ($cursec eq "maths");
      $cursec = "drop" if ($cursec eq "dropmailboxes");
      $cursec .= "_";
      $cursec = "" if ($cursec eq "general_");
      next;
   }
   my @line = split /:\s*/, $line;
   $line[0] = lc($line[0]);
   $line[0] =~ s/^\s+//;

   next if ($line[0] =~ /^((refuse)|(letterdigitcheckenabled)|(vowelconscheckenabled)|(account)|(password)|(onlyallowhightocctokens))/i);
   $line[0] =~ s/toccnomatchaadd/toccnomatchadd/;

   if ($line[0] =~ /^((accept)|(scan)|(ignore)|(veryshortemailspamext))$/i)
   {
      my $arr = $data{$cursec.$line[0]};
      if (!defined $arr)
      {
         $arr = [];
         $data{$cursec.$line[0]} = $arr;
      }
      push @{$arr}, $line[1];
   }
   else
   {
      if ($line[0] ne "specialflags")
      {
         $line[1] = "NO" if ($line[1] eq "0");
         $line[1] = "YES" if ($line[1] eq "1");
      }
      $data{$cursec.$line[0]} = $line[1];
   }
}
open OLD, ">pollustop.settings" or die "can't write new settings file";
select OLD;
print "{\n";
foreach my $key (sort keys %data)
{
   if (ref($data{$key}) eq "ARRAY")
   {
      print "  $key = (";
      print '"', join('","', @{$data{$key}}), '"';
      print ");\n";
   }
   else
   {
      print "  $key = \"$data{$key}\";\n";
   }
}
print "}\n";
close OLD;
