#!/usr/bin/perl

use XML::DOM;
use Connect;

$debug=0;

if(length(@ARGV)==0 ) {
  die("No file specified.\n");
}

$dbh = database_open();

my $file=$ARGV[0];
my $parser=new XML::DOM::Parser;

my $doc= $parser->parsefile($file);

my @fields=('depends',        [ 'profile-id' ],
            'package',        [ 'package-id' ]);


$profile_sql="insert into profiles values ( NULL, ? )";
$profile_sth=$dbh->prepare($profile_sql);

$dep1_sql="insert into prof_deps select ?, id from profiles where name=?";
$dep1_sth=$dbh->prepare($dep1_sql);

$pack1_sql="insert into prof_packs select ?, id from packages where idtxt=?";
$pack1_sth=$dbh->prepare($pack1_sql);

foreach my $profile ( $doc->getElementsByTagName("profile") ) {
  print "Profile: ";
  @sql=();
  foreach my $attribute ('id') {
    foreach my $value ( $profile->getAttributeNode($attribute) ) {
      if($value) {
        push @sql,$value->getValue;
        print "  $attribute: " . $value->getValue . "\n";
      }
    }
  }
  our $prof_id=add_profile(@sql);
  @sql=();
  $field_len=@fields;
  for ($i=0;$i<$field_len;$i+=2) {
    my $field=$fields[$i];
    my $attributes=$fields[$i+1];
    $attrib_data='';
    foreach my $branch ( $profile->getElementsByTagName($field)) {
      foreach my $attribute ( @$attributes ) {
        if($value=$branch->getAttributeNode($attribute)) {
          push @sql, $value->getValue;
          $attrib_data.="    $attribute: " . $value->getValue . "\n";
        }
      }
      $call_cmd="add_" . $field . "(" . $prof_id . ', @sql)';
      eval($call_cmd);
      @sql=();
    }
   # if($attrib_data) {
   #   print "  $field:\n";
   #   print $attrib_data;
   # }
  }
}

sub print_junk {
  my @data=@_;
  my $count=0;
  foreach my $junk ( @data ) {
    if($count) {
      print ",";
    } else {
      $count=1;
    }
    print $junk eq '' ? "NULL" : $junk;
  }
  print "\n";
}

sub add_profile {
  my @data=@_;
  if(!$debug) {
    $profile_sth->execute(@data) || die(join(',',@data));
    my $prof_id=$dbh->{mysql_insertid};
    return $prof_id;
  } else {
    print "add_profile():\n";
    print_junk(@data);
    return 1;
  }
}

sub add_depends {
  my @data=@_;
  if (!$debug) {
    $dep1_sth->execute($data[0],$data[1]);
  } else {
    print "add_depends():\n";
    print_junk(@data);
  }
  return 1;
}

sub add_package {
  my @data=@_;
  if (!$debug) {
    $pack1_sth->execute($data[0],$data[1]);
  } else {
    print "add_package():\n";
    print_junk(@data);
  }
  return 1;
}
