#!/usr/bin/perl -w
# -*- mode: perl; coding: utf-8 -*-
#
# Copyright (C) 2023 Elmar Hoffmann
#
# 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 2 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
#

=head1 NAME

dh_meta-depends - Generates meta:Depends and meta:Conflicts substvars

=cut

use strict;
use Cwd qw(realpath);
use Debian::Debhelper::Dh_Lib; # not in core

=head1 SYNOPSIS

B<dh_meta-depends> [S<I<debhelper options>>]

=head1 DESCRIPTION

B<dh_meta-depends> is a debhelper program which adds meta:Depends and
meta:Conflicts substvars from the meta-package relationships defined
in debian/meta.depends and debian/meta.conflicts.

=head1 NOTES

The best way to invoke B<dh_meta-depends> is by using B<dh --with=meta-depends>.

=head1 SEE ALSO

L<debhelper(7)>

=head1 AUTHORS

Elmar Hoffmann <elho@elho.net>

=cut

sub parse_depends {
    my $dependsfile = shift;

    return "" unless $dependsfile;

    my @depends;
    open(my $fh, $dependsfile) or return "";
    while (<$fh>) {
	chomp;
	next if /^\s*#/;
	next if /^\s*$/;
	push(@depends, $_);
    }
    close $fh;

    return  join ', ', @depends;
}


sub setsubstvarraw {
    my $package=shift;
    my $substvar=shift;
    my $line=shift;

    my $ext=pkgext($package);
    my $substvarfile="debian/${ext}substvars";

    complex_doit("(grep -a -s -v ${substvar} $substvarfile; echo ".escape_shell("${substvar}=$line").") > $substvarfile.new");
    rename_path("$substvarfile.new", $substvarfile);
}


init();

foreach my $package (@{$dh{DOPACKAGES}}) {
    my $dependsfile;
    my $conflictsfile;
    if ($package eq $dh{MAINPACKAGE}) {
	$dependsfile = "debian/meta.depends";
	$conflictsfile = "debian/meta.conflicts";
    } else {
	$dependsfile = pkgfile($package, "depends");
	$conflictsfile = pkgfile($package, "conflicts");
    }

    my $meta_depends = parse_depends($dependsfile);
    setsubstvarraw($package, "meta:Depends", $meta_depends);

    my $meta_conflicts = parse_depends($conflictsfile);
    setsubstvarraw($package, "meta:Conflicts", $meta_conflicts);
}
