#!/usr/bin/env python
# -*- coding: utf-8 -*-
##----------------------------------------------------------------------
## ./scripts/check-conf
## Check configuration files for errors
##----------------------------------------------------------------------
## Copyright (C) 2007-2011 The NOC Project
## See LICENSE for details
##----------------------------------------------------------------------

## Python modules
import os
import stat
import ConfigParser
import sys

# Settings
CONFIGS = ["noc.conf", "noc-sae.conf", "noc-activator.conf",
           "noc-classifier.conf", "noc-correlator.conf",
           "noc-notifier.conf"]
EXECUTABLES = ["ssh", "pg_dump", "tar", "gzip", "smidump", "smilint",
               "mongodump"]


def check_config():
    """
    Check configs.
    :returns: 0 - if success, 1 - if failed
    """
    # Check configs
    failed = []
    # Check config permissions
    for c in CONFIGS:
        path = os.path.join("etc", c)
        if os.path.isfile(path) and not os.access(path, os.R_OK):
            failed += ["%s: permission denied" % path]
    if failed:
        print "\n\t" + "\n\t".join(failed)
        return 1
    # Read config
    config = ConfigParser.SafeConfigParser()
    config.read(["etc/noc.defaults", "etc/noc.conf"])
    # Check executables
    for f in EXECUTABLES:
        path = config.get("path", f)
        if not os.path.isfile(path):
            failed += ["%s: %s is not found" % (f, path)]
        elif os.stat(path)[stat.ST_MODE] & stat.S_IXUSR == 0:
            failed += ["%s: %s is not executeble" % (f, path)]
    if failed:
        print "\n\t" + "\n\t".join(failed)
        return 1
    return 0

if __name__ == "__main__":
    sys.exit(check_config())
