#!@ido2db_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 IDOUtils 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.13.0";

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

	my $file="../mysql/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!";
	}

	# from 1.3.0 on we do that manually in the upgrade sqls for each rdbms itsself
	#print "** Updating table icinga_dbversion",$/;
	#$dbh->do("INSERT icinga_dbversion SET name='idoutils', version='$thisversion';");

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

