package Greenstone::Package::_pacman;

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

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

sub add_md5 {
    my $self = shift;
    my $md5 = Digest::MD5->new;
    for my $source (@_) {
        open my $MD5FH, '<', "$self->{output}/$source";
        binmode $MD5FH;
        $md5->addfile ($MD5FH);
        push @{$self->{config}->{SOURCE_SUMS}}, $md5->hexdigest;
        close $MD5FH
    }
}

sub add_sources {
    my $self = shift;
    $self->SUPER::add_sources;
    $self->{config}->{SOURCE_SUMS} = [];
    $self->add_md5 (@{$self->{config}->{SOURCES}});
}

sub add_makefile {
    my $self = shift;
    $self->SUPER::add_makefile;
    $self->add_md5 ('Makefile');
}

sub write_function {
    my ($name, $out, @lines) = @_;
    print $out $name, "() {\n";
    for my $line (@lines) {
        print $out "\t", $line, "\n";
    }
    print $out "}\n\n";
}

sub add_install {
    my $self = shift;
    if (exists $self->{config}->{PRE_INSTALL} or
        exists $self->{config}->{POST_INSTALL} or
        exists $self->{config}->{PRE_REMOVE} or
        exists $self->{config}->{POST_REMOVE}) {
        my $name = "$self->{config}->{NAME}.install";
        open my $INSTALL, '>', "/tmp/$name";
        exists $self->{config}->{PRE_INSTALL} and do {
            write_function "pre_install", $INSTALL, @{$self->{config}->{PRE_INSTALL}};
            write_function "pre_upgrade", $INSTALL, @{$self->{config}->{PRE_INSTALL}};
        };
        exists $self->{config}->{POST_INSTALL} and do {
            write_function "post_install", $INSTALL, @{$self->{config}->{POST_INSTALL}};
            write_function "post_upgrade", $INSTALL, @{$self->{config}->{POST_INSTALL}};
        };
        exists $self->{config}->{PRE_REMOVE} and
            write_function "pre_remove", $INSTALL, @{$self->{config}->{PRE_REMOVE}};
        exists $self->{config}->{POST_REMOVE} and
            write_function "post_remove", $INSTALL, @{$self->{config}->{POST_REMOVE}};
        close $INSTALL;
        $self->add ("/tmp/$name", "$self->{output}/$name");
        $self->{config}->{INSTALL} = "install=$name";
    } else {
        $self->{config}->{INSTALL} = "";
    }
}

1;
