#!/usr/bin/perl -w

# octave-pkg-dev.pl: Generate ${octave:Depends} variable and
#                    postinst/postrm scripts
# This file is part of the octave-pkg-dev Debian package

# Copyright (c) 2008, 2009, 2012, 2016  Rafael Laboissiere <rafael@laboissiere.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.


use strict;
use File::Find;
use Debian::Debhelper::Dh_Lib;
use MIME::Head;

init ();

my %depends = ();
my $desc = "";

my $octave_version = qx {/usr/bin/octave-config --print VERSION};
$octave_version =~ s/-rc/~rc/;

if (-f "DESCRIPTION") {

    my $fields = MIME::Head->new->from_file ("DESCRIPTION");

    my $deps = $fields->get ('depends');
    if (defined $deps) {
        map {
            if (/([^ ]+) \((.*)\)/) {
                $depends {"octave-$1"} = $2;
            } else {
                $depends {"octave-$_"} = "";
            }
        } grep {not /^octave/i} split (", ", $deps);
    }

    $desc = $fields->get ('description');
    $desc =~ s/\n */\n/g;
    chomp $desc;
    $desc =~ s/\n/\${Newline}/g;
}

foreach my $package (@{$dh{DOPACKAGES}}) {
    delsubstvar ($package, 'octave:Depends');
    addsubstvar ($package, 'octave:Depends', "octave (>= $octave_version)");
    for my $pkg (keys %depends) {
        # add dependencies from the DESCRIPTION file
        addsubstvar ($package, 'octave:Depends', $pkg, $depends {$pkg});
    }
    delsubstvar ($package, 'octave:Upstream-Description');
    addsubstvar ($package, 'octave:Upstream-Description', $desc);
}
