#!/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);

$host0_sql="select ifnull(max(priority),0)+1 from hosts";
$host0_sth=$dbh->prepare($host0_sql);
$host1_sql="insert into hosts select NULL, ?, ?, id from profiles where name=?";
$host1_sth=$dbh->prepare($host1_sql);

foreach my $host ( $doc->getElementsByTagName("host") ) {
  print "Host: ";
  @sql=();
  foreach my $attribute ( 'name','profile-id' ) {
    foreach my $value ( $host->getAttributeNode($attribute) ) {
      if($value) {
        push @sql,$value->getValue;
        print "  $attribute: " . $value->getValue;
      }
    }
  }
  our $host_id=add_host(@sql);
}

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_host {
  my @data=@_;
  ## @data position:         0       1         2       3         4         5
  ## $package_sth->execute('name','version','idtxt','reboot','priority','exeonce');
  # print "SUB: add_package()\n";
  $host0_sth->execute();
  ($nextpri)=$host0_sth->fetchrow_array;

  if(!$debug) {
    $host1_sth->execute($nextpri,@data) || die(join(',',@data));
    my $host_id=$dbh->{mysql_insertid};
    return $host_id;
  } else {
    print "add_host():\n";
    print_junk(@data);
    return 1;
  }
}
