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

# for testing
# use Smart::Comments;

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

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

use lib "/usr/local/share/request-tracker3.8/lib";
use lib "/usr/share/request-tracker3.8/lib";

use RT;
use RT::Record;

RT::LoadConfig;

my $config = RT->Config;
$config->Set(LogToScreen => 'error');

RT::Init;

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

my $class = RT::Record->new($RT::SystemUser);
$class->Table('FM_Classes');

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

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

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

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

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

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

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