#!@PERL@
#
# SYNTAX:
my $usage = "upgradedb -u user -p password -h hostname -d database";
#
# DESCRIPTION:
#	Runs upgrade scripts in this directory based on current level of database
#	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: 08/02/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";

# Create version table if it doesn't exist
eval { $dbh->do("SELECT * FROM icinga_dbversion LIMIT 1") };
if ($@) {
	print "*** Creating table icinga_dbversion",$/;
	$dbh->do("CREATE TABLE icinga_dbversion (name VARCHAR(10) NOT NULL, version VARCHAR(10) NOT NULL);");
};

# Get current database version
my $version;
my $thisversion="1.4b8";
my $lastversion="1.4b8";
my $legacyversion="1.4b8";

$version = $dbh->selectrow_array("SELECT version FROM icinga_dbversion WHERE name='ndoutils'");
if ($version eq "") {
	# Assume last legacy release (didn't have version table)
	print "*** Assuming version $legacyversion of nodutils installed",$/;
	$dbh->do("INSERT icinga_dbversion SET name='ndoutils', version='$legacyversion';");
	$version = $legacyversion
};

print "Current database version: $version",$/;

if ($version eq $thisversion){
    print "Database already upgraded.",$/;
    exit 0;
}


# Read upgrade script in the directory containing this script
my $file="mysql-upgrade-$version.sql";
if (-e $file){
	print "** DB upgrade required for $thisversion",$/;
	print "     Using $file for upgrade...",$/;
	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 "Upgrade from $file failed";
	print "** Upgrade to $thisversion complete",$/;
}
else{
	print "** No update script found for version $version - assuming none are required.",$/;
	print "** Upgrade to $thisversion complete",$/;
}

# Update db version record
$dbh->do("UPDATE icinga_dbversion SET version='$thisversion' WHERE name='ndoutils';");
