#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 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 version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# (c) 2015 Valentin Samir
import os
import sys
import argparse
from policyd_rate_limit.policyd import Policyd
from policyd_rate_limit import utils
from policyd_rate_limit.utils import config


if __name__ == "__main__":
    if os.getuid() == 0:
        try:
            utils.make_directories()
            utils.drop_privileges()
        except ValueError as error:
            sys.stderr.write("%s\n" % error)
            sys.exit(2)
    parser = argparse.ArgumentParser()
    parser.add_argument("--clean", help="clean old records from the database", action="store_true")
    parser.add_argument("--get_config", help="return the value of a config parameter")
    args = parser.parse_args()
    if args.get_config:
        try:
            sys.stdout.write(getattr(config, args.get_config))
        except AttributeError:
            sys.stderr.write("%s not found\n" % args.get_config)
            sys.exit(1)
    else:
        utils.database_init()
        if args.clean:
            utils.clean()
        else:
            utils.write_pidfile()
            p = Policyd()
            p.socket()
            try:
                p.run()
            except KeyboardInterrupt:
                pass
            p.close_socket()
            utils.remove_pidfile()

