#!/usr/bin/perl
# Plugin to kdesvn-build to setup needed software not installed on coverity test machines.
#
# Please also see the documentation that should be included with this program,
# from the kdesdk/doc/scripts/kdesvn-build directory.
#
# Copyright © 2003 - 2006 Michael Pyne. <michael.pyne@kdemail.net>
# Home page: http://kdesvn-build.kde.org/
#
# Copyright © 2006 Dirk Mueller <dirk@kde.org>
#
# You may use, alter, and redistribute this software under the terms
# of the GNU General Public License, v2 (or any later version).


# This subroutine checks if an appropriate dbus software is already installed.
# Currently this means DBUS 0.62. 
#
# Return value is true if DBUS is installed, 0 otherwise.

use strict;

sub check_dbus_installed()
{
    my $minVersion = '0.62';

    my $result = system('pkg-config', '--exists', "dbus-1 >= $minVersion");

    return ($result >> 8) == 0;
}

# Check that CLucene is installed.
# CLucene is required by Strigi in playground/base
sub check_clucene_installed()
{
    # this efficient check algorithm was copied from the cmake check
    my $minVersion = '0.9.16';

    my $result = system('pkg-config', '--exists', "clucene-core >= $minVersion");

    return ($result >> 8) == 0;
}

# Install CLucene
# CLucene is required by Strigi in playground/base
sub download_install_clucene()
{
    return download_install_tar('clucene-core', '0.9.16',
        "http://surfnet.dl.sourceforge.net/sourceforge/clucene", [ ] );
}

sub download_install_tar($$$$)
{
    return 1 if pretending;

    my ($module, $version, $baseurl, $module_command) = @_;

    note "\n<<<  Installing tarball $module  >>>\n";

    my $filename = "$module-$version.tar.gz";
    my $url = "$baseurl/$filename";

    my $tempdir = get_build_dir($module);
    if (! super_mkdir($tempdir)) {
        error "Unable to create temporary directory $tempdir.\n";
        return 0;
    }

    p_chdir($tempdir);
    pretend "Downloading $module to $tempdir/$filename";

    # Download snapshot.
    note "\tDownloading $module tarball.";

    if (not download_file($url, $filename))
    {
        error "Unable to download $module from r[$url]";
        return 0;
    }

    # Decompress.
    my $result = log_command($module, 'untar', ['tar', 'xvf', $filename]);
    if ($result != 0)
    {
        error "Unable to decompress $module tarball.";
        return 0;
    }

    my $prefix = get_option('global', 'kdedir');

    p_chdir("$module-$version");
    note "\tBuilding $module";
    my @command = ('./configure');
    push(@command, "--prefix=$prefix");
    push(@command, @{$module_command});

    $result = log_command($module, 'configure', \@command);

    if ($result != 0)
    {
        error "Unable to configure $module.";
        return 0;
    }

    $result = log_command($module, 'make', ['make']); 
    if ($result != 0)
    {
        error "Unable to build $module.";
        return 0;
    }

    note "\tInstalling $module (installing to $prefix)";
    $result = log_command($module, 'make-install', ['make', 'install']);
    if ($result != 0)
    {
        error "Unable to install $module.  (make-install-prefix is ignored).";
        return 0;
    }

    p_chdir (get_kdesvn_dir());
    prune_under_directory($tempdir);

    return 1;
}

# This subroutine downloads DBUS if necessary, and builds and installs it (all
# in one step: there is no separate update then install).
#
# It installs to the prefix given by the kdedir setting by default.
#
# This is normally only used for Coverity, as people should be installing
# dependency libraries using their distribution's package manager software, not
# kdesvn-build.
#
# Nothing happens in pretend mode however.
#
# Return value: 0 if the download/build/install failed, non-zero otherwise.
sub download_install_dbus()
{
    return download_install_tar('dbus', '0.62', "http://dbus.freedesktop.org/releases",
                             ['--disable-qt', '--disable-qt3', '--disable-dependency-tracking', 
			      '--disable-xml-docs', '--disable-doxygen-docs',
			      '--disable-glib', '--disable-mono', '--disable-python',
			      '--disable-gcj' ]
                             );
}

# This subroutine checks if an appropriate dbus software is already installed.
# Currently this means DBUS 0.62. 
#
# Return value is true if DBUS is installed, 0 otherwise.

sub check_cmake_installed()
{
    my $result = `cmake --version`;

    if ($result =~ /2.4-patch (\d+)/) {
        return 1 if ($1 >= 5);
    }

    if ($result =~ /2\.(\d+)-patch/) {
        return 1 if ($1 > 4);
    }

    return 0;
}

# This subroutine downloads CMake if necessary, builds and installs it (all
# in one step: there is no separate update then install).
#
# It installs to the prefix given by the kdedir setting by default.
#
# This is normally only used for Coverity, as people should be installing
# dependency libraries using their distribution's package manager software, not
# kdesvn-build.
#
# Nothing happens in pretend mode however.
#
# Return value: 0 if the download/build/install failed, non-zero otherwise.
sub download_install_cmake()
{
    return download_install_tar('cmake', '2.4.6', "http://www.cmake.org/files/v2.4", []);
}


sub check_lcms_installed()
{
    my $minVersion = '1.15';

    my $result = system('pkg-config', '--exists', "lcms >= $minVersion");

    return ($result >> 8) == 0;
}

sub download_install_lcms()
{
    return download_install_tar('lcms', '1.15', "http://www.littlecms.com/", []);
}

sub cleanup_soprano_mess()
{
    my $prefix = get_option('global', 'kdedir');

    if (-f "$prefix/include/Soprano") {

	unlink("$prefix/include/Soprano");
	return 1;
    }
    return 0;
}

# This subroutine is run after the lock has been obtained, but before performing
# any updates or builds.  Do any steps that need to be done only in the case of
# being run by Coverity.  This subroutine is only called if the COVERITY_RUN
# environment variable is set.
#
# No return value.
sub perform_coverity_checks()
{
    note "We are being run by g[Coverity].  Hi guys!";

    if (cleanup_soprano_mess()) {
	note "Soprano seems to have been messy installed. Cleaned install dir";
    }

    unless (check_dbus_installed())
    {
        note "D-BUS does not appear to be installed.  At least, pkg-config can't find it.";
        note "So just for you guys, I'll go ahead and install it for you.";

        if (not download_install_dbus())
        {
            error "\nWell, we were b[r[unable to install] DBUS for some reason.";
            error "Check your logs afterwards.";
        }
    }
    else
    {
        note "D-BUS appears to be installed. Continuing. ";
    }

    unless (check_cmake_installed())
    {
        note "CMake 2.4.3 does not appear to be installed.  At least its not in \$PATH";
        note "So just for you guys, I'll go ahead and install it for you.";

        if (not download_install_cmake())
        {
            error "\nWell, we were b[r[unable to install] CMake for some reason.";
            error "Check your logs afterwards.";
        }
    }
    else
    {
        note "cmake appears to be installed. Continuing. ";
    }


    unless (check_lcms_installed())
    {
        note "lcms 1.12 does not appear to be installed.  At least its not in pkg-config";
        note "So just for you guys, I'll go ahead and install it for you.";

        if (not download_install_lcms())
        {
            error "\nWell, we were b[r[unable to install] lcms for some reason.";
            error "Check your logs afterwards.";
        }
    }
    else
    {
        note "lcms appears to be installed. Continuing. ";
    }

    unless (check_clucene_installed())
    {
        note "CLucene does not appear to be installed.";
        if (not download_install_clucene())
        {
            error "\nCLucene can not be installed.";
            error "Check your logs afterwards.";
        }
    }

    # Print blank line.
    note "";
}

sub plugin_finish($)
{
    my ($logdir) = @_;
    my $today = basename($logdir);
    my $hostname = hostname();

=cut
    note "Uploading logfiles\n";
    system("svn", "import", "-m", $today,
           $logdir, "svn://kdorf.kde.org/home/coverity_kde/$today/$hostname") 
       if($hostname =~ /coverity/i);
=cut
}

sub plugin_setup_default_modules($$$)
{
    my ($update_list_ref, $build_list_ref, $package_opts_ref) = @_;

    foreach my $pack qw(kdevelop kdewebdev kdeaccessibility kdesdk kdereview)
# koffice playground/accessibility 
#                        playground/artwork playground/base playground/bindings playground/devtools 
#                        playground/edu playground/games playground/graphics playground/ioslaves 
#                        playground/multimedia playground/network playground/office playground/pim 
#                        playground/sysadmin playground/utils extragear/multimedia ) 
    {
	push(@$update_list_ref, $pack);
	push(@$build_list_ref, $pack);
        if (not exists $package_opts_ref->{$pack})
        {
            $package_opts_ref->{$pack} = { }; # Set up defaults
            $package_opts_ref->{$pack}{'set-env'} = { };
        }
    }
   
    # kdewebdev needs kdevelop
    $package_opts_ref->{'kdevelop'}{'install-after-build'} = 1;

    $package_opts_ref->{'qt-copy'} = {
        'configure-flags' => '-qt-gif -system-zlib -no-exceptions -fast -release',
        'apply-qt-patches' => 1,
        'use-unsermake' => 0,
        'use-cmake' => 0,
        'install-after-build' => 0,
        'set-env' => { },
        'make-options' => 'sub-src sub-tools'
    };

    # no xine-lib
    $package_opts_ref->{'kdebase'} = {
        "cmake-options" => "-DKDE4_DISABLE_MULTIMEDIA=ON"
    };

    $package_opts_ref->{'global'}{'use-cmake'} = 1;
    $package_opts_ref->{'global'}{'use-unsermake'} = 0;
}

sub plugin_update_module_path($)
{
    my ($module) = @_;
    my @revert_args = ('svn', 'revert', '-R', '.');
    run_svn($module, 'svn-revert', \@revert_args);
}

sub plugin_check_module_validity($$$)
{
    my ($module, $module_actual_url, $module_expected_url) = @_;

    if ($module_actual_url ne $module_expected_url)
    {
        warning "Something is wrong with your $module. Let's see if we can correct it. ";
        warning "kdesvn-build expects:        y[$module_expected_url]";
        warning "The module is actually from: y[$module_actual_url]";

        system("svn status --no-ignore | grep '^[I?]' | cut -b8- | xargs rm -rf");
        system("svn", "switch", $module_expected_url);
        return;
    }
}

perform_coverity_checks();
