#!/usr/bin/perl

use DBI;
use Data::Dumper;
use Time::ParseDate;
use POSIX;
use strict;

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

# Destination DB
my $tdb = DBI->connect("dbi:Pg:dbname=$ARGV[1]") or die;
$tdb->do("SET client_encoding=\'UTF8\'") or die;
$tdb->{AutoCommit}=0;

my $map_table = $ARGV[2] || 'migrate_map_1';
my $blogid = $ARGV[3] || 1;

# read MTpost-DrupalNode map

my $td = $tdb->selectall_hashref("select sourceid,destid from $map_table",'sourceid');
my %mt2drupal= map {$_,$td->{$_}->{destid}} keys %$td;
#print Dumper \%mt2drupal;

# Nodes
$tdb->do("delete from ljxp_node");
$tdb->do("delete from ljsync_node");

my $sel = $sdb->prepare("select * from lj_mapping where mt_blog_id=?");
my $i1 = $tdb->prepare("insert into ljxp_node (nid,ljid) values (?,?)");
my $i2 = $tdb->prepare("insert into ljsync_node (nid,jitemid,anum,ditemid) values(?,?,0,0)");
$sel->execute($blogid) or die;

my %jmap=();
while (my $d = $sel->fetchrow_hashref)
  {
    unless ($mt2drupal{$d->{mt_entry_id}})
      {
        print "No entry $d->{mt_entry_id} in mapping\n";
        next;
      }
    $i1->execute($mt2drupal{$d->{mt_entry_id}},$d->{lj_jitemid});
    $i2->execute($mt2drupal{$d->{mt_entry_id}},$d->{lj_jitemid});
    $jmap{$d->{lj_jitemid}}=1;
  }
$sel->finish;
$i1->finish;
$i2->finish;

# Copy comments. We've preserved comment numbers, so no mapping here
$sel = $sdb->prepare("select mt_comment_id,lj_commentid,lj_jitemid from lj_comments where mt_comment_id is not null") or die;
$tdb->do("delete from ljsync_comments") or die;
$sel->execute;
$i1 = $tdb->prepare("insert into ljsync_comments (jtalkid,cid) values(?,?)");
while (my $d = $sel->fetchrow_hashref)
  {
    next unless $jmap{$d->{lj_jitemid}};
    $i1->execute($d->{lj_commentid},$d->{mt_comment_id});
  }
$sel->finish;
$i1->finish;
$tdb->commit;

