#!/opt/alt/python27/bin/python2.7
# coding: utf-8

import sys

from argparse import ArgumentParser
from clcommon.sysctl import SysCtlConf, SYSCTL_CL_CONF_FILE


def create_parser():

    config_help = 'Path to sysctl config file. It\'s %(default)s by default'
    config_path = SYSCTL_CL_CONF_FILE

    parser = ArgumentParser(description='Utility for working with sysctl configs')
    subparsers = parser.add_subparsers(dest='command')

    subparser_set = subparsers.add_parser(name='set', help='Set or add the the sysctl parameter to the sysctl config',)
    subparser_set.add_argument('-P', '--parameter', action='store', required=True,
                               help='Name of the sysctl parameter')
    subparser_set.add_argument('-V', '--value', action='store', required=True,
                               help='Value of the sysctl parameter')
    subparser_set.add_argument('-C', '--config', action='store',
                               help=config_help,
                               default=config_path)


    subparser_get = subparsers.add_parser(name='get', help='Get the sysctl parameter')
    subparser_get.add_argument('-P', '--parameter', action='store', required=True,
                               help='Name of the sysctl parameter')
    subparser_get.add_argument('-C', '--config', action='store',
                               help=config_help,
                               default=config_path)


    subparser_remove = subparsers.add_parser(name='remove', help='Remove the sysctl parameter from the sysctl config')
    subparser_remove.add_argument('-P', '--parameter', action='store', required=True,
                                  help='Name of the sysctl parameter')
    subparser_remove.add_argument('-C', '--config', action='store',
                                  help=config_help,
                                  default=config_path)

    return parser


def _parse_args(argv):
    parser = create_parser()
    params = parser.parse_args(argv)
    return params


def main_(args):
    params = _parse_args(args)
    config_file = params.config
    command = params.command
    sysctl = SysCtlConf(config_file=config_file)
    if command == 'set':
        sysctl.set(name=params.parameter,
                   value=params.value)
    elif command == 'get':
        value = sysctl.get(name=params.parameter)
        print(value)
    elif command == 'remove':
        sysctl.remove(name=params.parameter)


def main():
    main_(sys.argv[1:])


if __name__ == '__main__':
    main()
