#!/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
from policyd_rate_limit.policyd import Policyd
from policyd_rate_limit.utils import clean


if __name__ == "__main__":
    if "--clean" in sys.argv[1:]:
        clean()
        sys.exit(0)
    else:
        try:
            with open("/var/run/policyd-rate-limit/policyd-rate-limit.pid", 'w') as f:
                f.write("%s" % os.getpid())
        except PermissionError:
            pass
        p = Policyd()
        p.socket()
        try:
            p.run()
        except KeyboardInterrupt:
            pass
        p.sock.close()
        try:
            os.remove("/var/run/policyd-rate-limit/policyd-rate-limit.pid")
        except OSError:
            pass
