#!/usr/bin/perl

# database fieldname vocabulary-ID [mapping-table]

use DBI;
use Data::Dumper;
use Time::ParseDate;
use POSIX;
use strict;
use locale;
POSIX::setlocale(LC_ALL,'ru_RU.KOI8-R');


# Source DB
my $db = DBI->connect("dbi:Pg:dbname=$ARGV[0]") or die;
$db->do("SET client_encoding=\'KOI8\'") or die;

my $field = $ARGV[1] || 'tags';
my $vid=$ARGV[2] || 1;
my $mapping = $ARGV[3] || 'migrate_map_1';

my $mtposts=$db->selectall_hashref("select m.destid as nid,p.$field as tags, p.title as title from mt_posts p inner join  migrate_map_1 m on m.sourceid=p.id",'nid');

my $tags = $db->selectall_hashref("select * from term_data where vid=?",'tid',undef,$vid);

my %name2tag;
#map {$name2tags{$tags->{$_}->{name}}=$_} keys %$tags;
map {$name2tag{lc($tags->{$_}->{name})}=$_} keys %$tags;
my @tagidlist = keys %$tags;
my $jtags="(".join(",",@tagidlist).")";

for my $nid(sort {$a<=>$b}keys %$mtposts)
  {
    my @l = split(/\,/,$mtposts->{$nid}->{tags});
    my @ids=();
    foreach my $t(@l)
      {
        if (exists $name2tag{lc $t})
          {
            push @ids,$name2tag{lc $t};
          }
        else
          {
            print "Unknown tag $t at $nid\n";
          }
      }
    my $n = $#l+1;
#    print "No tags for $nid\n" if $n<1;

    my $pc = $db->selectrow_array("select count(*) from term_node where nid=? and tid in $jtags",undef,$nid);
    if ($pc!=$n)
      {
        print "Fixing for $nid: $n $pc\n" if $pc != $n;
        $db->do("delete from term_node where nid=? and tid in $jtags",undef,$nid);
        foreach my $id(@ids)
          {
            $db->do("insert into term_node (nid,vid,tid) values (?,?,?)",undef,$nid,$nid,$id);
          }
        my $pc2 = $db->selectrow_array("select count(*) from term_node where nid=? and tid in $jtags",undef,$nid);
        print "Now: $n/$pc2\n";
      }
  }

