#!/usr/bin/env perl

use feature say;
use strict;
use Debian::Debhelper::Buildsystem::R qw(parse_deps);
use Dpkg::Control;
use Dpkg::Deps qw(deps_concat deps_parse);
use Getopt::Long;
use Pod::Usage;
use Switch;

sub maybe_write {
    my $fname = shift;
    my $content = shift;
    if ( -e $fname ) {
        say "W: $fname already exists, not rewriting";
        return 0;
    } else {
        open(my $fh, ">", $fname);
        say $fh $content;
        close $fh;
        say "I: writing $fname";
        return 1;
    }
}


my $opt_team = '';
my $opt_noteam = '';
my $opt_repo = '';
my $opt_help = 0;
my $opt_tests = '';

GetOptions('team=s' => \$opt_team, 'noteam' => \$opt_noteam, 'repo=s' => \$opt_repo,
           'help|?' => \$opt_help, 'tests=s' => \$opt_tests);
pod2usage(1) if $opt_help;

( -e "DESCRIPTION") or die "No DESCRIPTION file, is this an R package?";
my $desc = Dpkg::Control->new(type => Dpkg::Control::CTRL_UNKNOWN);
$desc->load("DESCRIPTION");

my $repo = "other";
if ($opt_repo) {
    $repo = $opt_repo;
    say "I: Using repo=$repo from --repo";
} elsif (length $desc->{Repository}) {
    # this appears to be set ("CRAN") for packages originating from CRAN,
    # but is not set for bioconductor, nor for packages direct from upstream
    $repo = $desc->{Repository};
    say "I: Using repo=$repo from DESCRIPTION::Repository";
} elsif (length $desc->{biocViews}) {
    # however, biocViews is (presumably) only going to be set for bioconductor
    # packages, so nonzero should identify
    $repo = "BIOC";
    say "I: Using repo=$repo due to existence of DESCRIPTION::biocViews";
} else {
    say "I: Using repo=$repo by default";
}

my $debname = "r-" . lc $repo . "-" . lc $desc->{Package};
say "I: Package source and binary name: $debname";

my @aptavail = qx/grep-aptavail -P -s Package -n -e ^r-/;
my %apthash;
@apthash{@aptavail} = ();

my $rdepends = deps_concat(Debian::Debhelper::Buildsystem::R::parse_depends("Depends", $desc->{Depends}, \%apthash));
my $rrecommends = deps_concat(Debian::Debhelper::Buildsystem::R::parse_depends("Recommends", $desc->{Recommends}, \%apthash));
my $rsuggests = deps_concat(Debian::Debhelper::Buildsystem::R::parse_depends("Suggests", $desc->{Suggests}, \%apthash));
my $rimports = deps_concat(Debian::Debhelper::Buildsystem::R::parse_depends("Imports", $desc->{Imports}, \%apthash));
my $builddeps;
if ( $rdepends ) {
    $builddeps = deps_concat("debhelper (>= 11~)", "dh-r", "r-base-dev", $rdepends, $rimports);
} else {
    $builddeps = deps_concat("debhelper (>= 11~)", "dh-r", "r-base-dev", $rimports);
}

say "I: Package depends: $rdepends";
say "I: Package imports: $rimports";
say "I: Package recommends: $rrecommends";
say "I: Package suggests: $rsuggests";
say "I: Package build-depends: $builddeps";

my $year = 1900 + (localtime)[5];
my $compiled = lc $desc->{NeedsCompilation} eq "yes";
my $arch =  $compiled ? "any" : "all";
if ($compiled) {
    say "W: This package NeedsCompilation: there are probably extra dependencies required";
    say "W: Package SystemRequirements: '$desc->{SystemRequirements}'";
}

my $longdesc = $desc->{Description};
$longdesc =~ s/^\s*/ /gm;

my $homepage = "";
if ($repo eq "CRAN") {
    $homepage = "https://cran.r-project.org/package=$desc->{Package}";
} elsif ($repo eq "BIOC") {
    $homepage = "https://bioconductor.org/packages/$desc->{Package}/";
} elsif ($repo eq "other") {
    $homepage = $desc->{URL};
}

my $maintainer = "$ENV{DEBFULLNAME} <$ENV{DEBEMAIL}>";
my $uploaders = "";
my $vcs = "";
my $vcsbrowser = "";

if ($opt_team eq "science") {
    say "I: Generating maintainers, uploaders, VCS entries for debian-science team";
    $uploaders = $maintainer;
    $maintainer = "Debian Science Maintainers <debian-science-maintainers\@lists.alioth.debian.org>";
    $vcsbrowser = "https://salsa.debian.org/r-pkg-team/$debname";
    $vcs = "https://salsa.debian.org/r-pkg-team/$debname.git";
    say "DEPRECATED OPTION: --team option is deprecated and will be removed in a soon future.";
    say "DEPRECATED OPTION: By default, dh-make-R defines fields for the new 'Debian R Packages Maintainers' team.";
} elsif ($opt_team eq "med") {
    say "I: Generating maintainers, uploaders, VCS entries for debian-med team";
    $uploaders = $maintainer;
    $maintainer = "Debian Med Packaging Team <debian-med-packaging\@lists.alioth.debian.org>";
    $vcsbrowser = "https://salsa.debian.org/r-pkg-team/$debname";
    $vcs = "https://salsa.debian.org/r-pkg-team/$debname.git";
    say "DEPRECATED OPTION: --team option is deprecated and will be removed in a soon future.";
    say "DEPRECATED OPTION: By default, dh-make-R defines fields for the new 'Debian R Packages Maintainers' team.";
} elsif (!$opt_noteam) {
    say "I: Generating maintainers, uploaders, VCS entries for debian-r team";
    $uploaders = $maintainer;
    $maintainer = "Debian R Packages Maintainers <r-pkg-team\@alioth-lists.debian.net>";
    $vcsbrowser = "https://salsa.debian.org/r-pkg-team/$debname";
    $vcs = "https://salsa.debian.org/r-pkg-team/$debname.git";
}

my $licensetext ;
switch ($desc->{License}) {
    case /^Artistic-2.0.*/	{ $desc->{License} = 'Artistic-2.0';
			  $licensetext = '
 Everyone is permitted to copy and distribute verbatim copies of this
 license document, but changing it is not allowed.
 .
 Preamble
 ********
 .
 This license establishes the terms under which a given free software
 Package may be copied, modified, distributed, and\/or redistributed.  The
 intent is that the Copyright Holder maintains some artistic control over
 the development of that Package while still keeping the Package
 available as open source and free software.
 .
 You are always permitted to make arrangements wholly outside of this
 license directly with the Copyright Holder of a given Package.  If the
 terms of this license do not permit the full use that you propose to
 make of the Package, you should contact the Copyright Holder and seek a
 different licensing arrangement.
 .
 Definitions
 ***********
 .
 "Copyright Holder" means the individual(s) or organization(s) named in
 the copyright notice for the entire Package.
 .
 "Contributor" means any party that has contributed code or other
 material to the Package, in accordance with the Copyright Holder\'s
 procedures.
 .
 "You" and "your" means any person who would like to copy, distribute, or
 modify the Package.
 .
 "Package" means the collection of files distributed by the Copyright
 Holder, and derivatives of that collection and\/or of those files.  A
 given Package may consist of either the Standard Version, or a Modified
 Version.
 .
 "Distribute" means providing a copy of the Package or making it
 accessible to anyone else, or in the case of a company or organization,
 to others outside of your company or organization.
 .
 "Distributor Fee" means any fee that you charge for Distributing this
 Package or providing support for this Package to another party.  It does
 not mean licensing fees.
 .
 "Standard Version" refers to the Package if it has not been modified, or
 has been modified only in ways explicitly requested by the Copyright
 Holder.
 .
 "Modified Version" means the Package, if it has been changed, and such
 changes were not explicitly requested by the Copyright Holder.
 .
 "Original License" means this Artistic License as Distributed with the
 Standard Version of the Package, in its current version or as it may be
 modified by The Perl Foundation in the future.
 .
 "Source" form means the source code, documentation source, and
 configuration files for the Package.
 .
 "Compiled" form means the compiled bytecode, object code, binary, or any
 other form resulting from mechanical transformation or translation of
 the Source form.
 .
 Permission for Use and Modification Without Distribution
 ********************************************************
 .
 (1) You are permitted to use the Standard Version and create and use
 Modified Versions for any purpose without restriction, provided that you
 do not Distribute the Modified Version.
 .
 Permissions for Redistribution of the Standard Version
 ******************************************************
 .
 (2) You may Distribute verbatim copies of the Source form of the
 Standard Version of this Package in any medium without restriction,
 either gratis or for a Distributor Fee, provided that you duplicate all
 of the original copyright notices and associated disclaimers.  At your
 discretion, such verbatim copies may or may not include a Compiled form
 of the Package.
 .
 (3) You may apply any bug fixes, portability changes, and other
 modifications made available from the Copyright Holder.  The resulting
 Package will still be considered the Standard Version, and as such will
 be subject to the Original License.
 .
 Distribution of Modified Versions of the Package as Source
 **********************************************************
 .
 (4) You may Distribute your Modified Version as Source (either gratis or
 for a Distributor Fee, and with or without a Compiled form of the
 Modified Version) provided that you clearly document how it differs from
 the Standard Version, including, but not limited to, documenting any
 non-standard features, executables, or modules, and provided that you do
 at least ONE of the following:
 .
 (a) make the Modified Version available to the Copyright Holder of the
 Standard Version, under the Original License, so that the Copyright
 Holder may include your modifications in the Standard Version.
 .
 (b) ensure that installation of your Modified Version does not prevent
 the user installing or running the Standard Version.  In addition, the
 Modified Version must bear a name that is different from the name of the
 Standard Version.
 .
 (c) allow anyone who receives a copy of the Modified Version to make the
 Source form of the Modified Version available to others under
 .
 (i) the Original License or
 .
 (ii) a license that permits the licensee to freely copy, modify and
 redistribute the Modified Version using the same licensing terms that
 apply to the copy that the licensee received, and requires that the
 Source form of the Modified Version, and of any works derived from it,
 be made freely available in that license fees are prohibited but
 Distributor Fees are allowed.
 .
 Distribution of Compiled Forms of the Standard Version or Modified
 ******************************************************************
 Versions without the Source
 ***************************
 .
 (5) You may Distribute Compiled forms of the Standard Version without
 the Source, provided that you include complete instructions on how to
 get the Source of the Standard Version.  Such instructions must be valid
 at the time of your distribution.  If these instructions, at any time
 while you are carrying out such distribution, become invalid, you must
 provide new instructions on demand or cease further distribution.  If
 you provide valid instructions or cease distribution within thirty days
 after you become aware that the instructions are invalid, then you do
 not forfeit any of your rights under this license.
 .
 (6) You may Distribute a Modified Version in Compiled form without the
 Source, provided that you comply with Section 4 with respect to the
 Source of the Modified Version.
 .
 Aggregating or Linking the Package
 **********************************
 .
 (7) You may aggregate the Package (either the Standard Version or
 Modified Version) with other packages and Distribute the resulting
 aggregation provided that you do not charge a licensing fee for the
 Package.  Distributor Fees are permitted, and licensing fees for other
 components in the aggregation are permitted.  The terms of this license
 apply to the use and Distribution of the Standard or Modified Versions
 as included in the aggregation.
 .
 (8) You are permitted to link Modified and Standard Versions with other
 works, to embed the Package in a larger work of your own, or to build
 stand-alone binary or bytecode versions of applications that include the
 Package, and Distribute the result without restriction, provided the
 result does not expose a direct interface to the Package.
 .
 Items That are Not Considered Part of a Modified Version
 ********************************************************
 .
 (9) Works (including, but not limited to, modules and scripts) that
 merely extend or make use of the Package, do not, by themselves, cause
 the Package to be a Modified Version.  In addition, such works are not
 considered parts of the Package itself, and are not subject to the terms
 of this license.
 .
 General Provisions
 ******************
 .
 (10) Any use, modification, and distribution of the Standard or Modified
 Versions is governed by this Artistic License.  By using, modifying or
 distributing the Package, you accept this license.  Do not use, modify,
 or distribute the Package, if you do not accept this license.
 .
 (11) If your Modified Version has been derived from a Modified Version
 made by someone other than you, you are nevertheless required to ensure
 that your Modified Version complies with the requirements of this
 license.
 .
 (12) This license does not grant you the right to use any trademark,
 service mark, tradename, or logo of the Copyright Holder.
 .
 (13) This license includes the non-exclusive, worldwide, free-of-charge
 patent license to make, have made, use, offer to sell, sell, import and
 otherwise transfer the Package with respect to any patent claims
 licensable by the Copyright Holder that are necessarily infringed by the
 Package.  If you institute patent litigation (including a cross-claim or
 counterclaim) against any party alleging that the Package constitutes
 direct or contributory patent infringement, then this Artistic License
 to you shall terminate on the date that such litigation is filed.
 .
 (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT
 HOLDER AND CONTRIBUTORS "AS IS\' AND WITHOUT ANY EXPRESS OR IMPLIED
 WARRANTIES.  THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT
 PERMITTED BY YOUR LOCAL LAW.  UNLESS REQUIRED BY LAW, NO COPYRIGHT
 HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
' ;
                        }
    case /^GPL-2/	{ $desc->{License} = 'GPL-2';
			  $licensetext = "
 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; version 2 of the License.
 .
 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.
 .
 On Debian systems you can find the full text of the GNU General Public
 License version 2 at /usr/share/common-licenses/GPL-2.
" ;
                        }
    case /^GPL$/	{ # expanded from GPL
                          $desc->{License} = 'GPL-2';
			  $licensetext = "
 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; version 2 of the License.
 .
 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.
 .
 On Debian systems you can find the full text of the GNU General Public
 License version 2 at /usr/share/common-licenses/GPL-2.
"                        }
    case /GPL \(>.*2\)/	{ $desc->{License} = 'GPL-2+';
			  $licensetext = "
 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.
 .
 On Debian systems you can find the full text of the GNU General Public
 License version 2 at /usr/share/common-licenses/GPL-2.
"                        }
    case /^GPL-3/	{ $desc->{License} = 'GPL-3';
			  $licensetext = "
 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.
 .
 On Debian systems you can find the full text of the GNU General Public
 License version 3 at /usr/share/common-licenses/GPL-3.
" ;
                        }
    case /^GPL \(>.*3\)/	{ $desc->{License} = 'GPL-3+';
			  $licensetext = "
 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.
 .
 On Debian systems you can find the full text of the GNU General Public
 License version 3 at /usr/share/common-licenses/GPL-3.
"                        }
    case /^LGPL-3/	{ $desc->{License} = 'LGPL-3';
			  $licensetext = "
 This program is free software: you can redistribute it and/or modify it 
 under the terms of the GNU Lesser General Public License as published by
 the Free Software Foundation version 3 of the License.  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.
 .
 On Debian systems you can find the full text of the GNU Lesser General
 Public License version 3 license at /usr/share/common-licenses/LGPL-3.
" ;
                        }
    case /^BSD_2_clause.*/	{ $desc->{License} = 'BSD-2-clause';
			  $licensetext = '
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met:
 .
    Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 .
    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and\/or other materials provided with the
    distribution.
 .
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
' ;                     }
    case /^BSD_3_clause.*/	{ $desc->{License} = 'BSD-3-clause';
			  $licensetext = '
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met:
 .
    Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 .
    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and\/or other materials provided with the
    distribution.
 .
    Neither the name of the <ORGANIZATION> nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.
 .
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
' ;                     }
    case /^MIT ?.*/	{ $desc->{License} = 'MIT';
			  $licensetext = '
 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and\/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:
 .
 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.
 .
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
' ;                     }
    case /Apache License 2.0/	{ $desc->{License} = 'Apache-2.0';
			  $licensetext = '
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 .
   http://www.apache.org/licenses/LICENSE-2.0
 .
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 .
 On Debian systems, the complete text of the Apache License, version 2.0
 can be found in /usr/share/common-licenses/Apache-2.0.
' ;                     }
    else		{
			  $licensetext = "
 FIXME: insert the appropriate license text
" ;
			}
}

# For some very strange reason the string "and/or" above needs to be escaped
# and this is now reverted.  Any clue how to do this more intelligently?
$licensetext =~ s?and\\/or?and/or?g ;

if (! -d "debian" ) {
    mkdir "debian";
    mkdir "debian/source";
    mkdir "debian/tests";
    say "I: Creating debian/";
}

$desc->{Author} =~ s/ +\[[^\]]+\]//g ;

my $copyrightend = $desc->{'Date/publication'} ;
if ( $copyrightend =~ /^$/ ) {
  $copyrightend = $desc->{'Packaged'} ;
}
$copyrightend =~ s/(\d\d\d\d)-.*/$1/;

my $dcontrol = <<"EOF";
Source: $debname
Maintainer: $maintainer
Uploaders: $uploaders
Section: gnu-r
Testsuite: autopkgtest-pkg-r
Priority: optional
Build-Depends: $builddeps
Standards-Version: 4.1.4
Vcs-Browser: $vcsbrowser
Vcs-Git: $vcs
Homepage: $homepage

Package: $debname
Architecture: $arch
Depends: \${R:Depends}, \${shlibs:Depends}, \${misc:Depends}
Recommends: \${R:Recommends}
Suggests: \${R:Suggests}
Description: $desc->{Title}
$longdesc
EOF

maybe_write("debian/control", $dcontrol);
maybe_write("debian/compat", "11");
maybe_write("debian/source/format", "3.0 (quilt)");

my $drules = <<"EOF";
#!/usr/bin/make -f

%:
\tdh \$\@ --buildsystem R
EOF

maybe_write("debian/rules", $drules);
chmod 0755, "debian/rules";

my $dwatch = "version=4\n";
if ($repo eq "CRAN") {
    $dwatch .= "https://cran.r-project.org/src/contrib/" . $desc->{Package} . '_([-\d.]*)\.tar\.gz';
} elsif ($repo eq "BIOC") {
    $dwatch .= 'opts=downloadurlmangle=s?^(.*)\.\.?https:$1packages/release/bioc? \\' . "\nhttps://bioconductor.org/packages/release/bioc/html/$desc->{Package}.html .*/$desc->{Package}_(.*).tar.gz";
} elsif ($repo eq "other") {
    $dwatch .= "FIXME: $homepage";
}

maybe_write("debian/watch", $dwatch);

my $dcopy = <<"EOF";
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: $desc->{Package}
Upstream-Contact: $desc->{Maintainer}
Source: $homepage

Files: *
Copyright: (FIXME: year)-$copyrightend $desc->{Author}
License: $desc->{License}

Files: debian/*
Copyright: $year $ENV{DEBFULLNAME} <$ENV{DEBEMAIL}>
License: $desc->{License}

License: $desc->{License}$licensetext
EOF

maybe_write("debian/copyright", $dcopy);

if ( -e "debian/changelog") {
    say "W: debian/changelog already exists, not rewriting";
} else {
    qx/dch --create --package $debname -v $desc->{Version}-1 "Initial release (closes: #xxxxxx)"/;
    say "I: Writing debian/changelog";
}

my $test_generic = <<'EOF';
#!/bin/sh -e

for testfile in tests/*.R; do
    echo "BEGIN TEST $testfile"
    LC_ALL=C.UTF-8 R --no-save < $testfile
done
EOF

my $test_run_unit_test = <<"EOF";
#!/bin/sh -e

pkgname=$desc->{Package}
debname=$debname

if [ "\$AUTOPKGTEST_TMP" = "" ] ; then
    AUTOPKGTEST_TMP=`mktemp -d /tmp/\${debname}-test.XXXXXX`
    trap "rm -rf \$AUTOPKGTEST_TMP" 0 INT QUIT ABRT PIPE TERM
fi
cd \$AUTOPKGTEST_TMP
cp -a /usr/share/doc/\$debname/tests/* \$AUTOPKGTEST_TMP
gunzip -r *
for testfile in *.R; do
    echo "BEGIN TEST \$testfile"
    LC_ALL=C R --no-save < \$testfile
done
EOF

my $test_bioc = <<"EOF";
#!/bin/sh -e

LC_ALL=C R --no-save -e 'BiocGenerics:::testPackage("$desc->{Package}")'
EOF

my $test_vignette = <<"EOF";
#!/bin/sh -e

for vignette in \$(find vignettes -iname '*.rnw' -or -iname '*.rmd'); do
    echo "BEGIN VIGNETTE \$vignette"
    LC_ALL=C R CMD Sweave \$vignette
done
EOF

my %autopkgtests;

# detect common test dependencies
my $testpkgs = "@,";
if ($rsuggests =~ /testthat/) {
    $testpkgs .= " r-cran-testthat,";
}
if ($rsuggests =~ /runit/) {
    $testpkgs .= " r-cran-runit,";
}

if ($opt_tests =~ /generic/) {
    maybe_write("debian/tests/generic", $test_generic);
    $autopkgtests{"generic"} = $testpkgs;
}
if ($opt_tests =~ /run-unit-test/) {
    maybe_write("debian/tests/run-unit-test", $test_run_unit_test);
    maybe_write("debian/docs", "debian/tests/run-unit-test\ntests");
    $autopkgtests{"run-unit-test"} = $testpkgs;
}
if ($opt_tests =~ /bioc/) {
    maybe_write("debian/tests/bioc", $test_bioc);
    $autopkgtests{"bioc"} = $testpkgs . " r-bioc-biocgenerics";
}
if ($opt_tests =~ /vignette/) {
    maybe_write("debian/tests/vignette", $test_vignette);
    if ($rsuggests =~ /knitr/) {
        $autopkgtests{"vignette"} = "@, r-cran-knitr";
    } else {
        $autopkgtests{"vignette"} = "@";
    }
}

my $testcontrol = "";
foreach my $key (keys %autopkgtests) {
    $testcontrol .= "Tests: $key\n";
    $testcontrol .= "Depends: $autopkgtests{$key}\n";
    $testcontrol .= "Restrictions: allow-stderr\n\n";
}

maybe_write("debian/tests/control.autodep8", $testcontrol);

if ( $testcontrol eq "" ) {
  `rm -rf debian/tests`;
}

__END__

=head1 NAME

dh-make-R - Generates a debian/ directory skeleton for R packages

=head1 SYNOPSIS

dh-make-R [options]

 Options:
    --help
    --team TEAM          Set packaging team
    --noteam             Set no packaging team
    --repo REPO          Override R repository detection
    --tests TEST1,TEST2  Generate autopkgtest templates

=head1 OPTIONS

=over 8

=item B<--help>

Print this help message.

=item B<--team>

DEPRECATED.
Generate default maintainer, uploaders, VCS URLs for the given packaging team.
Understood values are "science" and "med" for debian-science and debian-med
respectively.

=item B<--noteam>

By default, dh-make-R defines fields for the new 'Debian R Packages Maintainers' team.
However, if you don't want to team maintain your package, you can use --noteam option
to leave relevant fields blank.

=item B<--repo>

Set the R repository (used in the package name), overriding automatic detection.

=item B<--tests>

Comma-separated list of test templates to generate. Understood values are
"generic" (run tests/*.R), "run-unit-test" (installs tests as documentation,
can be run outside autopkgtest), "bioc" (runs BiocGenerics::testPackage) and
"vignette" (attempts to rebuild documentation).

=back

=head1 DESCRIPTION

B<dh-make-R> should be run from the root of an unpacked R tarball (ie, the
directory containing DESCRIPTION). Values from this are used to generate
default control, compat, copyright, rules, source/format and watch files.
