package Greenstone::Package::_apt;

use strict;
use warnings;
use utf8;
use parent 'Greenstone::Package';

sub replacement_array {
    my $self = shift;
    my $array = shift;
    return join ", ", @{$array};
}

sub write_function {
    my ($self, $name, @lines) = @_;
    open OUT, '>', "/tmp/$name";
    for my $line (@lines) {
        print OUT $line, "\n";
    }
    close OUT;
    chmod 0755, "/tmp/$name";
    $self->add ("/tmp/$name", "$self->{output}/debian/$name");
}

sub add_install {
    my $self = shift;
    exists $self->{config}->{PRE_INSTALL} and
        $self->write_function ("preinst", @{$self->{config}->{PRE_INSTALL}});
    exists $self->{config}->{POST_INSTALL} and
        $self->write_function ("postinst", @{$self->{config}->{POST_INSTALL}});
    exists $self->{config}->{PRE_REMOVE} and
        $self->write_function ("prerm", @{$self->{config}->{PRE_REMOVE}});
    exists $self->{config}->{POST_REMOVE} and
        $self->write_function ("postrm", @{$self->{config}->{POST_REMOVE}});
}

sub add_package_section {
    my ($self, $out) = @_;
    for my $line (
        'Package: %NAME%',
        'Architecture: %ARCHITECTURE%',
        'Homepage: %HOMEPAGE%',
        'Depends:',
        '%DEPENDS',
        'Description: %DESCRIPTION_SHORT',
        '  %DESCRIPTION'
    ) {
        my $copy = $line;
        $self->subst ($copy);
        print $out $copy, "\n";
    }
}

sub add_package_impl {
    my ($self, $packages) = @_;
    $self->add_install;
    open my $CONTROL, '>', "/tmp/gspkg.control";
    for my $line (
        'Source: %NAME%',
        'Section: java',
        'Priority: optional',
        'Maintainer: %MAINTAINER_NAME% <%MAINTAINER_EMAIL%>',
        'BuildDepends:',
        '%MAKEDEPENDS%',
    ) {
        my $copy = $line;
        $self->subst ($copy);
        print $CONTROL $copy, "\n";
    }
    if (defined $packages) {
        my $config = $self->{config};
        for my $package (@{$packages}) {
            $package->{HOMEPAGE} = $config->{HOMEPAGE};
            $self->{config} = $package;
            $self->add_package_section ($CONTROL);
        }
        $self->{config} = $config;
    } else {
        $self->add_package_section ($CONTROL);
    }
    close $CONTROL;
    $self->add ("/tmp/gspkg.control", "$self->{output}/debian/control");
}

1;
