#!/usr/bin/env python3

import pprint
import sqlite3
from termcolor import cprint,colored
import sys
import os
import datetime
import xml.etree.ElementTree as et
import atexit
import re
import socket

from utils import smmsutils,smmssqlutils

def eprint(*args, **kwargs):
	print(*args, file=sys.stderr, **kwargs)

def cleanup(pidfile):
	###	clean up
	os.remove(pidfile)

def main():
	pp = pprint.PrettyPrinter(indent=4)

	pidfile = '/tmp/store.pid.run'
	if os.path.exists(pidfile):
		eprint(colored("PID file exists.  Is store already running?", "red", attrs=['bold']))
		raise Exception("Verify if the program is currently running and/or delete the file at {}".format(pidfile))

	atexit.register(cleanup, pidfile)
	### set pid file
	with open(pidfile, 'w') as pidf:
		pidf.write(str(os.getpid()))

	today = datetime.datetime.now()
	dd = int(today.strftime('%s')) - 86400
	last_24 = datetime.datetime.fromtimestamp(dd)
	working_dir = '/root/tools/smms'
	dbfile = '{}/stores.db'.format(working_dir)
	files_to_process = []

	### findall *.xml files in protocol directories
	for root, dirs, files in os.walk(working_dir):
		for file in files:
			if file.endswith('.xml'):
				files_to_process.append(os.path.join(root, file))

	# set up/connect to the DB
	db = smmssqlutils.smmssqlutils(dbtype='sqlite3', dbfile=dbfile)
	#print(str(dir(db)))
	db.dbsetup()
	print("""dbtype: {0}
dbfile: {1}
server: {2}
database: {3}
user: {4}
pass: {5}
port: {6}""".format (db.dbtype, db.dbfile, db.host, db.database, \
	db.user, db.passw, db.port))

	filecount = len(files_to_process)
	print("Found {} files to process.".format(filecount))
	### Loop through the files
	for f in files_to_process:
	###		read in the xml
		print(str(filecount))
		print("Collecting IPs from file: {}".format(f))
		addrs = smmsutils.smmsutils.get_xml_addrlist(f)
		filecount -= 1

	addrcount = len(addrs)
	print("Found {} addresses to check and/or store.".format(addrcount))
	###		check if nost in db
	for a in addrs:
		print(str(addrcount))
		if db.host_exists(a):
			host_id = db.get_host_id(a)
			print("Host exists: {} ({})".format(a, host_id))
		else:
	###		add if not
			fields = {}
			if a.count('.') == 3 and \
				re.search(r'(?:\d{1,3}\.){3}\d{1,3}', a) is not None:
				fields['ip_addr'] = a
				fields['hostname'] = None
				try:
					fields['hostname'] = str(socket.gethostbyaddr(a)[0])
				except socket.herror as err:
					fields['hostname'] = 'unresolved'
			fields['first_found'] = str(today.strftime('%s'))
			fields['last_found'] = str(today.strftime('%s'))
			fields['service_status'] = 'up'
			db.add_host(fields)
		addrcount -= 1

if __name__=='__main__':
	main()
