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 Cwd;

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

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_compat( $self->debian_file('compat') );
    $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("lisp");
    $src->Priority("optional");
    $src->Testsuite("autopkgtest-pkg-elpa");
    $src->Standards_Version( $self->debstdversion );
    $src->Build_Depends->add( "debhelper (>= 10)" );
    $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();

    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}, emacs, ${elpa:Depends}';

        # append depends that aren't included in ${elpa:Depends}
        $depends .= ", dash-el"
          if fgrep { /^;; Package-Requires: .*\(dash \"/ } @files;
        $depends .= ", s-el"
          if fgrep { /^;; Package-Requires: .*\(s \"/ } @files;

        my $stanza = { Package           => "elpa-$bin",
                       Architecture      => "all",
                       Depends           => "$depends",
                       Built_Using       => '${misc:Built-Using}',
                       Recommends        => "emacs (>= 46.0)",
                       Enhances          => "emacs, emacs24",
                       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 3 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;
}

1;
