package DhMakeELPA::Command::make;

use strict;
use warnings;
no warnings "experimental::smartmatch";

use Debian::Control;
use File::Spec::Functions qw(catfile);
use Email::Date::Format qw(email_date);
use File::Grep qw(fgrep);
use File::Find::Rule;
use Cwd;

use base 'DhMakeELPA::Command::Packaging';

=head1 NAME

DhMakeELPA::Command::make - implementation of 'dh-make-elpa make'

=cut

sub execute {
    my $self = shift;

    # extract basic information from package
    $self->main_dir(getcwd());
    $self->extract_basic;

    # initial sanity check
    die "debian/ subdir already exists!  Won't clobber it.\n"
      if ( -d $self->debian_dir );

    # now start writing out package data
    mkdir( $self->debian_dir, 0755 )
      or die "Cannot create " . $self->debian_dir . " dir: $!\n";
    $self->create_elpa();
    $self->write_source_format(
        catfile( $self->debian_dir, 'source', 'format' ) );
    $self->create_changelog( $self->debian_file('changelog'),
        $self->cfg->closes // $self->get_wnpp( $self->pkgname ) );
    $self->create_rules();
    $self->create_control();
    $self->create_copyright();
    $self->create_docs();
    $self->create_watch();
    $self->create_gbp_conf() if $self->cfg->pkg_emacsen;

    return(0);
}

sub create_control {
    my $self = shift;
    my $src = $self->control->source;

    $src->Source( $self->pkgname );
    $src->Section("editors");
    $src->Priority("optional");
    $src->Standards_Version( $self->debstdversion );
    $src->Build_Depends->add( sprintf "debhelper-compat (= %s)", $self->cfg->dh );
    $src->Build_Depends->add( "dh-elpa" );
    $src->Build_Depends->add( "elpa-buttercup" )
      if ( $self->detect_buttercup_tests() );
    $src->Homepage( $self->homepage ) if ( defined $self->homepage );

    $self->fill_maintainer();
    $self->fill_vcs();

    # simple checks for existence of Buttercup or ERT tests, based on
    # code in dh_elpa_test
    my $rule = File::Find::Rule->new;
    $rule
      ->file()
      ->name( '*.el' )
      ->or(
           # ERT
           File::Find::Rule ->grep( "\\(ert-deftest" ),
           # Buttercup
           File::Find::Rule ->grep( "\\(describe \"" )
          );
    $src->Testsuite("autopkgtest-pkg-elpa") if ( $rule->in('.') );

    foreach my $bin (keys %{$self->bins}) {
        my @files = @{$self->bins->{$bin}};
        # resolve special case so we can use fgrep
        @files = glob($self->main_dir . "/*.el")
          if ( @files ~~ ["*.el"] );

        my ($short_desc, $long_desc) =
          $self->extract_description( $self->main_file("$bin.el") );
        my $depends = '${misc:Depends}, ${elpa:Depends}';

        my $stanza = { Package           => "elpa-$bin",
                       Architecture      => "all",
                       Depends           => "$depends",
                       Recommends        => "emacs (>= 46.0)",
                       Enhances          => "emacs",
                       short_description => "$short_desc",
                       long_description  => "$long_desc",
                     };
        # black magic from dh-make-perl:
        $self->control->binary_tie->Push( $bin => Debian::Control::Stanza::Binary->new($stanza) );
    }

    $self->control->write( $self->debian_file('control') );
}

sub create_changelog {
    my ( $self, $file, $bug ) = @_;

    my $fh = $self->_file_w($file);

    my $closes = $bug ? "  (Closes: #$bug)" : '';
    my $changelog_dist = $self->cfg->pkg_emacsen ? "UNRELEASED" : "unstable";

    $fh->printf( "%s (%s) %s; urgency=medium\n",
        $self->pkgname, $self->elpa_version . "-1", $changelog_dist );
    $fh->print("\n  * Initial release.$closes\n\n");
    $fh->printf( " -- %s  %s\n", $self->get_developer,
        email_date(time) );

    $fh->close;
}

# ELPA packages are almost always GPL-2+ or GPL-3+, so for now those
# are the only cases we support
sub create_copyright {
    my $self = shift;
    my ( $gpl_version, @res );
    if ( defined $self->gpl_version ) {
        $gpl_version = $self->gpl_version;
    } else {
        # give up
        return;
    }

    my $fh = $self->_file_w( $self->debian_file("copyright") );
    my $year = (localtime)[5] + 1900;

    push @res, 'Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/';
    push @res, 'Upstream-Name: ' . $self->pkgname;
    push @res, 'Source: ' . $self->homepage if ( defined $self->homepage );
    push @res, "";
    push @res, 'Files: *';
    push @res, 'Copyright: ' . $self->copyright;
    push @res, 'License: GPL-' . $gpl_version . '+';
    push @res, "";
    push @res, 'Files: debian/*';
    push @res, "Copyright: (C) $year " . $self->get_developer;
    push @res, 'License: GPL-' . $gpl_version . '+';
    push @res, "";
    push @res, 'License: GPL-' . $gpl_version . '+';
    push( @res,
          " 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 $gpl_version 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, see <http://www.gnu.org/licenses/>.",
          " .",
          " On Debian systems, the complete text of the GNU General",
          " Public License version $gpl_version can be found in `/usr/share/common-licenses/GPL-$gpl_version'",
        );

    push( @res,
          "",
          "DISCLAIMER: This copyright info was automatically extracted",
          " from the ELPA package.  It might not be accurate.  You need",
          " to throughly verify that the code passes the DFSG, and that",
          " the info in this file is accurate.",
          "NOTE: Don't forget to remove this disclaimer when you've",
          " performed this verification."
          );

    $fh->print( join( "\n", @res, '' ) );
    $fh->close;
}

=head1 COPYRIGHT & LICENSE

=over

=item Copyright (C) 2016-2018 Sean Whitton <spwhitton@spwhitton.name>

=back

It is slightly based on the corresponding part of dh-make-perl, which
is originally copyrighted as follows:

=over 4

=item Copyright (C) 2000, 2001 Paolo Molaro <lupus@debian.org>

=item Copyright (C) 2002, 2003, 2008 Ivan Kohler <ivan-debian@420.am>

=item Copyright (C) 2003, 2004 Marc 'HE' Brockschmidt <he@debian.org>

=item Copyright (C) 2005-2007 Gunnar Wolf <gwolf@debian.org>

=item Copyright (C) 2006 Frank Lichtenheld <djpig@debian.org>

=item Copyright (C) 2007-2014 Gregor Herrmann <gregoa@debian.org>

=item Copyright (C) 2007,2008,2009,2010,2011,2012,2015 Damyan Ivanov <dmn@debian.org>

=item Copyright (C) 2008, Roberto C. Sanchez <roberto@connexer.com>

=item Copyright (C) 2009-2010, Salvatore Bonaccorso <carnil@debian.org>

=item Copyright (C) 2013, Axel Beckert <abe@debian.org>

=back

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License version 2 as published by the Free
Software Foundation.

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
Street, Fifth Floor, Boston, MA 02110-1301 USA.

=cut

1;
