#!/usr/bin/perl -w

use strict;
use DBI;
$| = 1;

my $user='user';
my $pass = 'password';
my $siteid = 5662; 

my $newdbh = DBI->connect("DBI:mysql:database=DADADATABASENAME",'DADAUSER',
'DADAPASSWORD');
my $olddbh = DBI->connect("DBI:mysql:database=IMCDATABASENAME",'IMCUSERNAME',
'IMCPASSWORD');
my ($firstnewid, $lastnewid);

my $query = "select id, title, image_url, link_1, link_2, link_3, body,
  timestamp, image_caption, link_1_title, link_2_title, link_3_title,
  language, sub_title
  from FEATURES
  where site_id = $siteid";
my $sth = $olddbh->prepare($query);
$sth->execute();
print "articles selected, parsing and insering...";
while (my @r = $sth->fetchrow_array) {
  # 
  # Append any links to the bottom of the body
  #
  if($r[2]) {
    $r[6] = "<img src=\"$r[2]\" alt=\"$r[8]\" border=\"0\" align=\"right\">" . $r[6];
  }
  if ($r[3] and $r[9]) {
    $r[6] .= "<br>[ <a href=\"$r[3]\">$r[9]</a>";
  }
  if ($r[4] and $r[10]) {
    $r[6] .= " | <a href=\"$r[4]\">$r[10]</a>";
  }
  if ($r[5] and $r[11]) {
    $r[6] .= " | <a href=\"$r[5]\">$r[11]</a>";
  }
  if ($r[3] and $r[9]) {
    $r[6] .= " ]";
  }
  my $date;
  if ($r[7] =~ /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/) {
    $date = "$1-$2-$3 $4:$5:$6";
  } else {
    warn "bad time for article $r[0]\n";
  }

  $r[1] .= ": " . $r[13];
  #print "I see article $r[1], time $r[7]/$date\n$r[6]\n";
  
  #
  # Puts all into 'miscellaneous' category, sets to displayable,
  # makes all features.
  #
  $query = "insert into articles
    (created_datetime, edit_datetime, 
     heading, summary, 
      displayable, 
     feature, mime_type)
    values 
    (?, ?, 
     ?, ?, 
      1, 
     1, 'text/html')";
  my $in_sth = $newdbh->prepare($query);
  $in_sth->execute($date, $date, $r[1], $r[6]);
  #
  # get id of just-inserted row so media can be inserted
  #
  $query = "select max(objectid) from articles";
  $in_sth = $newdbh->prepare($query);
  $in_sth->execute();
  my ($newid) = $in_sth->fetchrow_array;
  $firstnewid = $newid if (! $firstnewid);
  $lastnewid = $newid;
  if ($r[2]) {
        $query = "insert into media (parentid, filename, caption, remote)
          values (?,?,?,1)";
        $in_sth = $newdbh->prepare($query);
        $in_sth->execute($newid, $r[2], $r[8]);
  }
}
print "done! The objectid of the first record inserted was $firstnewid,
and the last was $lastnewid.\n";
