#! /usr/bin/env perl

use strict;

use CGI qw/:standard/;
use IO::LockedFile;
use HTML::Entities;

use Email::Sender::Simple qw(sendmail);
use Email::Simple;
use Email::Simple::Creator;

my $db_file = '/tmp/fortunes';
my $from = 'Fortuner <soft.rez@listes.ens-lyon.fr>';
my $to = 'Fortuner <oschwand@chadok.info>';

sub display_form {
    my $text = shift;
    print start_html(
			-title => 'Fortunes',
        -head  => meta({ -http_equiv => 'Content-Type',
                         -content    => 'text/html; charset=utf-8' }
        )
        ), "\n";

    print
        div({style => "text-align:center"},
            h1 "Les fortunes de l'ENS Lyon"
        ),
            p, a({href => "fortunes-view.cgi"}, "Retour aux fortunes"),
            div({style => "text-align:center"},
                h2 'Ajouter une nouvelle fortune',
            ),

            div({style => "text-align:center"},
                start_form(), "\n",
                p, textarea(
                    -name      => 'fortune',
                    -id        => 'fortune',
                    -default   => "La fortune\n   -- #plop (ma sœur)",
                    -rows      => 8,
                    -columns   => 80,
                    -maxlength => 2048,
                ), "\n",
                br(), "\n",

                p, submit, "\n",

                endform(), "\n",
            );

    if ($text) {
        $text = decode_entities($text);
        my $html = join("<br />\n", split(/\n/, $text));
        print
            hr,
            p, $html,
            hr;
    }

    print
        end_html(), "\n";
}

sub get {
    my $text = decode_entities(param('fortune'));
    chomp $text;
    return $text;
}

sub add {
    my $text = shift;
    my $db = new IO::LockedFile('>>'.$db_file);
    print $db "%\n";
    print $db $text, "\n";
    $db->close();

    return $text;
}

sub update {
    system('strfile', $db_file);
}

sub notify {
    my $text = shift;
    my $email = Email::Simple->create(
        header => [
            To      => $to,
            From    => $from,
            Subject => "Nouvelle fortune",
        ],
        body => "$text\n",
        );
    sendmail($email);
}

print header,  "\n";
if (param()) {
   my $text = get;
   add $text;
   display_form $text;
   update;
   notify $text;
}
else {
    display_form;
}

