#!/usr/bin/env python3
#
# Check that a limit file is valid.
#
# Usage: validate-limits [ FILE ]
#
# Where FILE is the path to the limits file to be validated or '-' for
# standard input.  If none is provided, the system default limit file
# will be read.
#

import optparse
import pscheduler
import sys

from pscheduler.limitprocessor.limitprocessor import LimitProcessor

pscheduler.set_graceful_exit()

#
# Gargle the arguments
#

class VerbatimParser(optparse.OptionParser):
    def format_epilog(self, formatter):
        return self.epilog

opt_parser = VerbatimParser(
    usage="Usage: %prog [ FILE ]",
    epilog=
"""
Examples:

  validate-limits /foo/bar/limits.conf
      Validate /foo/bar/limits.conf

  validate-limits -
      Validate limit configuration from the standard input

  validate-limits
      Validate /etc/pscheduler/limits.conf if readable.
"""
    )
opt_parser.disable_interspersed_args()

opt_parser.add_option("--quiet",
                      help="Print nothing if successful",
                      action="store_true",
                      dest="quiet")

(options, remaining_args) = opt_parser.parse_args()

try:
    if len(remaining_args) == 0:
        infile = open("/etc/pscheduler/limits.conf", 'r')
    elif len(remaining_args) == 1 and remaining_args[0] == '-':
        infile = sys.stdin
    elif len(remaining_args) == 1:
        infile = open(remaining_args[0], 'r')
    else:
        opt_parser.print_usage()
        pscheduler.fail()

except IOError as ex:
    pscheduler.fail("Unable to read input: %s" % (str(ex)))

try:
    processor = LimitProcessor(infile)
except Exception as ex:
    pscheduler.fail(f'Limit configuration is invalid:\n{str(ex)}')

if sys.stdout.isatty() and not options.quiet:
    print("Limit configuration is valid.")

pscheduler.succeed()
