#!/usr/bin/perl -w
use strict;

# for testing
# use Smart::Comments;

# test if the database has the AssetTracker schema modifications 
# exit codes:
# 0: OK for AssetTracker 2.0
# 1: missing
# 2: needs upgrade from 1.2

# this script intentionally doesn't use any modules from AssetTracker
# itself, just in case we want to use it in the preconfiguration
# phase some day


use Getopt::Std;

my %opts;

getopts('v:', \%opts) or usage();

sub usage {
    print STDERR <<EOF;
Usage: $0 [ -v ( 3.4 | 3.6 | 3.8 | 4 )]
EOF
    exit 1;
}

my $rt_version = "4";
if (exists $opts{v}) {
    if ($opts{v} =~ /^(3\.[468]|4)$/) {
        $rt_version = $1;
    } else {
        usage();
    }
}

unshift @INC, "/usr/local/share/request-tracker${rt_version}/lib";
unshift @INC, "/usr/share/request-tracker${rt_version}/lib";

require RT;
require RT::Record;

RT::LoadConfig();
RT::Init();

# we don't want the errors in the RT log
local $SIG{__WARN__} = sub {};

my $type = RT::Record->new($RT::SystemUser);
$type->Table('AT_Types');

my ($status, $msg) = $type->Load(0);
## type/status: $status
## type/msg:    $msg

if ($status != 0) {
    print "strange database state: type 0 loaded succesfully?\n";
    exit 42;
}

if ($msg =~ /execute query/i) {
    print "AssetTracker schema missing\n";
    exit 1;
}

my $scrip = RT::Record->new($RT::SystemUser);
$scrip->Table('AT_Scrips');
($status, $msg) = $scrip->Load(0);
## scrip/status: $status
## scrip/msg:    $msg

if ($msg =~ /execute query/i) {
    print "AssetTracker schema needs an upgrade for 2.0\n";
    exit 2;
}

if ($status || ($msg =~ /find row/i)) {
    print "AssetTracker schema ok\n";
    exit 0;
}

print "unknown database state\n";
exit 3;
