#!/usr/bin/python3

from ipblockHelpers import *
import config

from pygtail import Pygtail

import pymysql
import ssl
import warnings                   # To filter mysql warnings
import sys                        # For args
import os.path                    # To check if file exists
import datetime
import time                       # For Sleep
import yaml
import argparse
import re
import socket

from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver


warnings.filterwarnings('ignore')
config.pot = socket.gethostbyaddr(socket.gethostname())[0].split(".")[0]


#######################################################
#      Parse Arguments
#######################################################
if not parseArgs():
    sys.exit(1)


#  Read ConfigFile data
readConfigData()
if len(config.ConfigData) == 0:
    print("Error: No configuration found in %s" % config.args.configFile)
    sys.exit(1)


# Read each entry from configFile
try:
    config.env   = config.ConfigData['env']
    config.svc   = config.ConfigData['svc']
    mysqlhost    = config.ConfigData['mysqlhost']
    mysqlport    = config.ConfigData['mysqlport']
    mysqluser    = config.ConfigData['mysqluser']
    mysqlpass    = config.ConfigData['mysqlpass']
    mysqldb      = config.ConfigData['mysqldb']
    mysqltimeout = config.ConfigData['mysqltimeout']
    if config.args.logLevel != -1:
        config.logLevel = int(config.args.logLevel)
    else:
        config.logLevel = int(config.ConfigData['logLevel'])
    sleepTimer     = config.ConfigData['sleepTimer']
    servicePort    = config.ConfigData['servicePort']
    serverVersion  = config.ConfigData['serverVersion']
    sysVersion     = config.ConfigData['sysVersion']
    sendResponse   = config.ConfigData['sendResponse']

except KeyError:
    print("Error: Missing argument:", sys.exc_info()[1])
    sys.exit(1)
except:
    print("Error: %s" % sys.exc_info()[1])
    sys.exit(1)


#  Other Variables
regExIP                 = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
config.tableNameSuspect = "suspect_" + config.env
logDir                  = "/var/log/ipblock-" + config.env


#  Create DB connection
if not createDBconnection(mysqlhost, mysqlport, mysqluser, mysqlpass, mysqldb, mysqltimeout):
    sys.exit(1)


#######################################################
#
#   Main Code
#
#######################################################
if not os.path.exists(logDir):
    os.makedirs(logDir, mode=0o700, exist_ok=True)

if not os.path.exists("/var/lib/ipblock"):
    os.makedirs("/var/lib/ipblock", mode=0o700, exist_ok=True)


config.activitylogFileFH = open(logDir + '/service-' + config.svc + '.log', "a")
try:
    writeLog(1, "action=\"starting service\" pot=%s" % config.pot)
except:
    print("Error: Unable to write to error log. %s" % sys.exc_info()[1])
    sys.exit(1)


class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        auth = self.headers.get('Authorization')
        self.send_response(sendResponse)
        for header in config.ConfigData['headers']:
            for headerKey in header:
                self.send_header(headerKey, header[headerKey])


        self.end_headers();
    def log_message(self, format, *args):
        return

class MyHandler(SimpleHTTPRequestHandler):
    server_version   = serverVersion
    sys_version      = sysVersion
    def handle_one_request(self):
        addToSuspect(str(self.client_address[0]))
        return SimpleHTTPRequestHandler.handle_one_request(self)


Count = 10
while Count > 1:
    try:
        httpd = socketserver.TCPServer(("", servicePort), MyHandler)
        Count = -1
    except:
        writeLog(1, "action=\"starting service\" msg=\"warning:%s retrying\"" % sys.exc_info()[1])
        Count -= 1
        time.sleep(10)

    if Count == 0:
        writeLog(1, "action=\"starting service\" msg=\"error: %s\"" % sys.exc_info()[1])
        sys.exit(1)


while True:
    httpd.handle_request()

    config.activitylogFileFH.flush()
    time.sleep(sleepTimer)
