#! /usr/bin/env perl

use strict;
use warnings;

use Pod::Usage;
use Getopt::Long;
use Net::IMAP::Simple;
use Term::ReadPassword;

=encoding utf8

=head1 NAME

lsimap - List mailboxes on a remote IMAP server

=head1 VERSION

Version 0.1

=cut

our $VERSION = '0.1';

=head1 DESCRIPTION

List mailboxes on a remote IMAP server.

=head1 SYNOPSIS

lsimap [options] host

=head1 OPTIONS

=over

=item B<-h, --help>

Display this help text

=item B<-V, --version>

Display the version number

=item B<-p, --port>

Set the port for the connection to the server (default 143 or 993 with
SSL)

=item B<-u, --user>

Username

=item B<-s, --ssl>

Use SSL or TLS

=item B<-F, --format>

Display results using the given format (%s will be replaced by the name
of the mailbox)

=back

=cut

my $user = undef;
my $host = undef;
my $port = undef;
my $ssl = 0;
my $format = "%s";
my $help = 0;
my $version = 0;

GetOptions("p|port=i"   => \$port,
           "u|user=s"   => \$user,
           "s|ssl!"     => \$ssl,
           "F|format=s" => \$format,
           "h|help"     => \$help,
           "V|version"  => \$version,
    );

if ($version) {
    print <<EOF;
lsimap (part of lsmail tools) $VERSION
Copyright (C) 2011 Olivier Schwander <olivier.schwander\@chadok.info>
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
EOF
exit(0);
}

if ($help) {
    pod2usage({
        -exitval => 0,
        -verbose => 1,
              })
}

$host = shift;

if (! $host) {
    pod2usage({
        -exitval => 2,
        -verbose => 0,
              })
}

if (! $port) {
    if ($ssl) {
        $port = 993;
    }
    else {
        $port = 143;
    }
}

my $imap = Net::IMAP::Simple->new($host,
                                  port => $port,
                                  use_ssl => $ssl,
    ) ||
    die "Unable to connect to IMAP: $Net::IMAP::Simple::errstr\n";

my $pass = read_password("Password for " . $user . "@" . $host . ": ");
$imap->login($user, $pass) ||
    die "Login failed: " . $imap->errstr . "\n";

foreach ($imap->mailboxes) {
    s/^\"//;
    s/\"$//;
    print sprintf($format, $_), "\n";
}

=head1 AUTHOR

Olivier Schwander, C<< <olivier.schwander@chadok.info> >>

=head1 BUGS

Please report any bugs or feature requests on the Redmine page of the
project L<http://redmine.chadok.info/projects/lsmail>.

=head1 COPYRIGHT & LICENSE

Copyright 2011 Olivier Schwander, all rights reserved.

This program is free software; you can redistribute it and/or modify it
under the terms of the GPLv3+ licence.

=cut

