#!/usr/bin/env python3

# Python swap manager
# Copyright (c) 2018-2018, Mickael Badet
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     * Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice,this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the copyright holder nor the names of its
#       contributors may be used to endorse or promote products derived from
#       this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import sys
from swappy import __version__
from swappy import swapcheck_main, SwapInfo
from optparse import OptionParser, IndentedHelpFormatter


# ----------------------------------------------------------------------------------------------------------------------
class BannerHelpFormatter(IndentedHelpFormatter):
    """Just a small tweak to optparse to be able to print a banner."""
    def __init__(self, banner, *argv, **argd):
        self.banner = banner
        IndentedHelpFormatter.__init__(self, *argv, **argd)

    def format_usage(self, usage):
        msg = IndentedHelpFormatter.format_usage(self, usage)
        return '%s\n%s' % (self.banner, msg)


# ----------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
    # Parse the command line arguments.
    formatter = BannerHelpFormatter(
        "Python script to check linux swap pressure\n"
        "By Mickael Badet (prog at mickbad dot com)\n"
        "https://github.com/mickbad/swappy\n"
    )
    parser = OptionParser(formatter=formatter)
    parser.set_usage("%prog [options] /path/to/config.yml")
    parser.add_option("--info", default=False,
                      action="store_true",
                      help="show in stdout swap files if alert [default=False]")
    parser.add_option("--simulate", default=False,
                      action="store_true",
                      help="simulate resetting swap [default=False]")
    (options, args) = parser.parse_args()
    params = [(k, v) for (k, v) in options.__dict__.items() if not k.startswith('_')]
    params = dict(params)

    # Récupération du fichier de configuration
    config_pathname = args[0] if len(args) > 0 else "/etc/swappy.yml"
    simulation = params["simulate"] == True
    display_stdout = params["info"] == True

    # démarrage du programme
    try:
        print("Swap Checker v{}".format(__version__))
        print("swap pressure: {:.2f}%".format(swapcheck_main(config_pathname,
                                                             simulation=simulation,
                                                             display_stdout=display_stdout)))

    except Exception as e:
        print("\n** Something went wrong:\n{}".format(str(e)))
        print("try to see options with --help")
        print("Exiting.\n")
