import boto3, os, sys, socket, traceback, subprocess
from run_phc import delete_sqs_message
from common import write_pidfile_or_die, assume_role, sqs_assume_role_client, remove_pidfile

def queue_dc():
	sqscredentials=assume_role("assumequeueSQS")
	sqs_client=sqs_assume_role_client(sqscredentials)
	queue_url='https://sqs.us-west-2.amazonaws.com/673385534282/Clio_Queue_DataCollection'
	message = sqs_client.receive_message(QueueUrl=queue_url, MessageAttributeNames=['All'])
	for data in message.get('Messages'):
		sqs_message_receipt_handle = data.get('ReceiptHandle')
		database = data.get('MessageAttributes').get('database').get('StringValue')
		fqdn=data.get('MessageAttributes').get('fqdn').get('StringValue')
		schema=data.get('MessageAttributes').get('schema').get('StringValue')
		time=data.get('MessageAttributes').get('time').get('StringValue')
		schema=data.get('MessageAttributes').get('schema').get('StringValue')
		database_type=data.get('MessageAttributes').get('db_type').get('StringValue')
		does_fqdn_match(database, fqdn, schema, time, database_type, sqs_message_receipt_handle, sqs_client, queue_url)

def does_fqdn_match(database, fqdn, schema, time, database_type, sqs_message_receipt_handle, sqs_client, queue_url):
	if fqdn == str(socket.getfqdn()):
		delete_sqs_message(sqs_client, queue_url, sqs_message_receipt_handle)
		write_pidfile_or_die("/var/lib/postgresql/healthcheck/datacollection.pid")
		subprocess.check_call(['stdbuf', '-oL', '-eL', '/var/lib/postgresql/healthcheck/datacollection.sh', schema, 'm', time, fqdn, database, '|', 'logger', '-p''local2.info', '-t', 'datacollection'])
	else:
		print "fqdn does not match"
		sys.exit()

def check_for_pidfile():
	pid = str(os.getpid())
	pidfile = "/var/lib/postgresql/healthcheck/datacollection.pid"  
	if os.path.isfile(pidfile):
		print "%s already exists, exiting" % pidfile
		sys.exit()

#### execution of main
if __name__ == '__main__':

	try:
		check_for_pidfile()
		queue_dc()
		remove_pidfile("/var/lib/postgresql/healthcheck/datacollection.pid")
	except Exception as e:
		traceback.print_exc()
		exit(1)
