#!/usr/bin/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 IDOUtils 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 IF NOT EXISTS icinga_dbversion (dbversion_id serial, name varchar(10) character set latin1  default '', version varchar(10) character set latin1  default '', create_time timestamp default '0000-00-00 00:00:00', modify_time timestamp default '0000-00-00 00:00:00', PRIMARY KEY (dbversion_id), UNIQUE KEY dbversion (name)) ENGINE=InnoDB;");
};

# Get current database version
my $version;
my $thisversion = "1.7.0";
my $legacyversion = "1.7.0";

$version = $dbh->selectrow_array("SELECT version FROM icinga_dbversion WHERE name='idoutils'");
if ($version eq "") {
	# Assume last legacy release (didn't have version table)
	print "*** Assuming version $legacyversion of idoutils installed",$/;
	$dbh->do("INSERT INTO icinga_dbversion (name, version, create_time, modify_time) VALUES ('idoutils', '$legacyversion', NOW(), NOW()) ON DUPLICATE KEY UPDATE version='$legacyversion', modify_time=NOW();");
	$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/mysql-upgrade-$thisversion.sql";
if (-e $file){
	print "** DB upgrade required for $thisversion",$/;
    while ($version lt $thisversion) {
        opendir(UPGRADE, "../mysql/upgrade/") || die "Can not open upgrade directory";
        our @a = readdir(UPGRADE);
        @a = sort(@a);
        foreach(@a) {
            $_ =~ m/mysql-upgrade-(.*).sql/g;
            my $upgradeversion = $1;
            if ($upgradeversion ge $version){
                my $file="../mysql/upgrade/mysql-upgrade-$upgradeversion.sql";
                $version = $upgradeversion;
                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 "     Database version is now: $version",$/;
            }
        }
        close UPGRADE;
    }
    print "** Upgrade to $thisversion complete",$/;
} else{
    print "** No update script found for version $version - assuming none are required.",$/;
    print "** Upgrade to $thisversion complete",$/;
}

# from 1.3.0 on we do that manually in the upgrade sqls for each rdbms itsself
# Update db version record
#$dbh->do("UPDATE icinga_dbversion SET version='$thisversion' WHERE name='idoutils';");
