#!/usr/bin/perl
# Copyright 2006-2016 Canonical Ltd.
# Copyright 2023 Simon McVittie
# SPDX-License-Identifier: GPL-2.0-or-later

# Usage: parse-deps.pl DEPS ARCH depends|build-depends
# Parse DEPS as a Depends or Build-Depends string, and print
# dependencies suitable for DEBIAN/control on stdout.
# Example:
# ./parse-deps.pl "a (>= 1), b [i386], c [amd64], d <!nocheck>" i386 depends
# ->
# a (>= 1), b, d

use strict;
use warnings;

use Dpkg::Deps;

# The dpkg-dev in Debian 8 supported profiles but Ubuntu 14.04 did not, so
# we can drop this check when Ubuntu 14.04 'trusty' is no longer interesting
my $supports_profiles = ($Dpkg::Deps::VERSION gt '1.04' or 0);

my $origdeps = shift;
my $arch = shift;
my $mode = shift;

$origdeps =~ s/(^|,)[^<,]+<[^!,>]+>//g if (!$supports_profiles);

my @args;
if ($mode eq 'build-depends') {
    push @args, reduce_profiles => $supports_profiles, build_dep => 1;
}

my $dep = deps_parse($origdeps, reduce_arch => 1, host_arch => $arch, @args);
my $out = $dep->output();
# fall back to ignoring build profiles
$out =~ s/ <![^ >]+>//g if (!$supports_profiles);
print $out, "\n";
