#! /usr/bin/env python

#
#    Postfix queue control python tool (pymailq)
#
#    Copyright (C) 2014 Denis Pompilio (jawa) <denis.pompilio@gmail.com>
#
#    This file is part of pymailq
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of the GNU General Public License
#    as published by the Free Software Foundation; either version 2
#    of the License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, see <http://www.gnu.org/licenses/>.

import argparse
import pymailq
from pymailq import shell, store


SUMMARY = """
====================== Mail queue summary ========================
Total mails in queue: {total_mails}
Total queue size in MB: {total_mails_size:.3}

----- Mails by status ----------    ----- Mails by size ----------
Active      {active_mails:<18}      Average size  {average_mail_size:10.3f} KB
Hold        {hold_mails:<16}        Maximum size  {max_mail_size:10.3f} KB
Deferred    {deferred_mails:<20}    Minimum size  {min_mail_size:10.3f} KB

----- Unique senders -----------    ----- Unique recipients ------
Senders     {unique_senders:<20}    Recipients    {unique_recipients:>10}
Domains     {u_s_domains:<17}       Domains       {u_r_domains:>10}

----- Top senders ------------------------------------------------
{top_senders}

----- Top sender domains -----------------------------------------
{top_sender_domains}

----- Top recipients ---------------------------------------------
{top_recipients}

----- Top recipient domains --------------------------------------
{top_recipient_domains}
"""


def main():
    """main function"""
    cli = shell.PyMailqShell()
    cli.cmdloop_nointerrupt()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Postfix queue control shell')
    parser.add_argument('--version', dest='version', action='store_const',
                        const=True, default=False,
                        help='show shell version')
    parser.add_argument('--debug', dest='debug', action='store_const',
                        const=True, default=False,
                        help='show shell debug and timing info')
    parser.add_argument('--config', dest='cfg_file',
                        help='specify a configuration file for PyMailq')
    parser.add_argument('--summary', dest='summary', action='store_const',
                        const=True, default=False,
                        help='summarize the mails queue content')

    args = parser.parse_args()

    if args.version:
        print("Shell version: %s" % pymailq.VERSION)
        exit()

    if args.debug:
        print("Setting shell in debug mode.")
        pymailq.DEBUG = True

    if args.cfg_file:
        print("Using custom configuration: " + str(args.cfg_file))
        pymailq.load_config(args.cfg_file)

    if args.summary:
        pstore = store.PostqueueStore()
        pstore.load()
        data = pstore.summary()
        data['total_mails_size'] /= 1024*1024.0
        data['average_mail_size'] /= 1024.0
        data['max_mail_size'] /= 1024.0
        data['min_mail_size'] /= 1024.0
        data['u_s_domains'] = data['unique_sender_domains']
        data['u_r_domains'] = data['unique_recipient_domains']
        for status in data['top_status']:
            data[status[0] + '_mails'] = status[1]

        ranks = ['top_senders', 'top_sender_domains',
                 'top_recipients', 'top_recipient_domains']
        for key in ranks:
            data[key] = "\n".join(["%-5s  %s" % (value[1], value[0])
                                   for value in data[key]])

        print(SUMMARY.format(**data))
        exit()

    main()
