#!/usr/bin/perl

use strict;
use warnings;

use Mail::Sendmail;

use lib qw(LATMOS-Accounts/lib);

use LATMOS::Accounts;

my $version = $LATMOS::Accounts::VERSION;
my $dest = 'link-accounts-discuss@forge.ipsl.jussieu.fr';

my $subject = "New Link::Accounts release: $version";

my $message = <<EOF;

A new version of Link::Account has been released.

You can download it here:

http://forge.ipsl.jussieu.fr/link-accounts/web/release/$version

http://forge.ipsl.jussieu.fr/link-accounts/web/release/$version/latmos-accounts-$version-1mdv2010.0.noarch.rpm
http://forge.ipsl.jussieu.fr/link-accounts/web/release/$version/latmos-accounts-web-$version-1mdv2010.0.noarch.rpm

Regards.

EOF

sub parse_changes {
    my ($files) = @_;

    my $text = '';

    if (open(my $handle, '<', $files)) {
        while(my $line = <$handle>) {
            if ($line =~ /^$version\s*$/) {
                while ($line = <$handle>) {
                    $line =~ /^\S/ and last;
                    $text .= $line;
                }
                last;
            }
        }
        close($handle);
    }

    return $text
}

if (my $changes = parse_changes('LATMOS-Accounts/Changes')) {
    if ($changes) {
        $message .= "\nChanges for Link::Accounts\n";
        $message .= $changes;
    } else {
        $message .= "\nNo changes reported for Link::Accounts\n";
    }
}
if (my $changes = parse_changes('LATMOS-Accounts-Web/Changes')) {
    if ($changes) {
        $message .= "\nChanges for Link::Accounts Web Application\n";
        $message .= $changes;
    } else {
        $message .= "\nNo changes reported for Link::Accounts Web application\n";
    }
}

print $message;

print "Press enter to send message\n";

<>;

if (!Mail::Sendmail::sendmail(
    To => $dest,
    Subject => $subject,
    Message => $message,
    From => 'link-accounts-devel@forge.ipsl.jussieu.fr',
    smtp => 'mailhost',
)) {
    die "Cannot send mail: " . $Mail::Sendmail::error . "\n";
}
