#!/usr/bin/python3

from ipblockHelpers import *
import config

from pygtail import Pygtail
from binascii import hexlify

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
import yaml
import argparse
import re
import socket
import os
import select


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'])
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, "svc=%s action=\"starting service\" pot=%s" % (config.svc, config.pot))
except:
    print("Error: Unable to write to error log. %s" % sys.exc_info()[1])
    sys.exit(1)

#  Delay startup to make sure "real" services start first
time.sleep(10)


socks = []
servicePort = []
for i in config.ConfigData['servicePorts']:
    servicePort.append(i)


for i in range(len(servicePort)):
    socks.append(socket.socket( socket.AF_INET, socket.SOCK_STREAM ))
    try:
        socks[i].bind( ('',servicePort[i]) )
        socks[i].listen(1)
        writeLog(5, "svc=%s-%d action=\"bind and listen\"" % (config.svc, servicePort[i]))
    except OSError as err:
        writeLog(5, "svc=%s-%d action=\"bind and listen\" msg=\"socket in use, skipping\"" % (config.svc, servicePort[i]))
        socks[i].close()
    except:
        writeLog(5, "svc=%s-%d action=\"bind and listen\" msg=\"error: %s\"" % (config.svc, servicePort[i], sys.exc_info()[1]))
        socks[i].close()


workingSocks = []
for i in range(len(servicePort)):
    if socks[i].fileno() != -1:
        workingSocks.append(socks[i])


while True:
    ready_socks,_,_ = select.select(workingSocks, [], [])
    for sock in ready_socks:
        conn, addr = sock.accept()
        addToSuspect(str(addr[0]),port=sock.getsockname()[1] )
        conn.close()

    config.activitylogFileFH.flush()
