#!@PERL@
#
# SYNTAX:
my $usage = "installdb -u user -p password -h hostname -d database";
#
# DESCRIPTION:
#	Runs installation script in this directory
#	Options as mysql's for authentication
#
# COPYRIGHT:
#	Copyright (C) 2005 Altinity Limited
#	Copyright is freely given to Ethan Galstad if included in the NDOUtils distribution
#
# LICENCE:
#	GNU GPLv2
#
# Last Updated: 03/21/2007
#


use strict;
use FindBin qw($Bin);
use Getopt::Std;
use DBI;

sub usage {
	print $usage,$/,"\t",$_[0],$/;
	exit 1;
}

my $opts = {};
getopts("u:p:h:d:", $opts) or usage "Bad options";

my $database = $opts->{d} || usage "Must specify a database";
my $hostname = $opts->{h} || "localhost";
my $username = $opts->{u} || usage "Must specify a username";
my $password = $opts->{p};
usage "Must specify a password" unless defined $password;	# Could be blank

# Connect to database
my $dbh = DBI->connect("DBI:mysql:database=$database;host=$hostname",
		$username, $password,
		{ RaiseError => 1 },
		)
		or die "Cannot connect to database";

# Current database version
my $thisversion="1.4b8";

# Create version table if it doesn't exist
eval { $dbh->do("SELECT * FROM icinga_dbversion LIMIT 1") };
if ($@) {

	my $file="mysql.sql";
	if (-e $file){
	    print "** Creating tables for version $thisversion",$/;
	    print "     Using $file for installation...",$/;
	    my $p = "-p$password" if $password;	# Not required if password is blank
	    system("mysql -u $username $p -D$database -h$hostname < $file") == 0 or die "Installation from $file failed";
	}
	else{
	    die "No installation script found!";
	}

	print "** Updating table icinga_dbversion",$/;
	$dbh->do("INSERT icinga_dbversion SET name='ndoutils', version='$thisversion';");

	print "Done!",$/;
}
else {
    print "*** Database already installed",$/;
    exit 0;
};

