#!/usr/bin/env python

'''
@name: process_toBeArchivedList.py
@author: Patrick Pascual (ppascual@slac.stanford.edu)
@created: 05/22/2015

@description: An automated script to categorize a list of PVs requested through the EDM GUI. The PVs are separated into Photon group and LCLS group categories. Photon PVs are automagically emailed to the Photon Group, while LCLS PVs are added to the EPICS Archiver manually via the Archiver Appliance web UI. Log files are saved under the following directory structure by default:

/u1/lcls/tools/ArchiveBrowser
	|
	|--> toBeArchivedLogs
		|
		|--> unarchivedPVs (leftover PVs not belonging to Photon, LCLS, or waveform lists)
		|
		|--> photonPVs (PVs to be emailed to Photon Group)
		|
		|--> lclsPVs (PVs to be added to LCLS Archiver)
		|
		|--> facetPVs (PVs to be added to FACET Archiver)
		|
		|--> waveformPVs (waveform PVs, not being added to the Archiver for now)
		|
		|--> unprocessedPVs (saving the original input PV list)

'''

import argparse
import json
import operator
import os
import re
import shutil
import smtplib
import socket
import string
import sys
import urllib
import urllib2
import time

from datetime import date

class ValidationError(Exception):
	def __init__(self, value):
		self.value = value
	def __str__(self):
		return repr(self.value)

class ChannelAccessConnectionError(Exception):
	def __init__(self, value):
		self.value = value
	def __str__(self):
		return repr(self.value)

class ChannelAccessInfoError(Exception):
	def __init__(self, value):
		self.value = value
	def __str__(self):
		return repr(self.value)

# Initialize PV log directory and subdirectories
def InitPVLogs(rootdir):
	pv_log_dirs = {}

	print 'in InitPVLogs: rootdir = {}'.format(rootdir)
	pv_log_dirs['rootdir'] = os.path.join(rootdir, 'toBeArchivedLogs')
	pv_log_dirs['unprocessed_pv_dir'] = os.path.join(pv_log_dirs['rootdir'], 'unprocessedPVs')
	pv_log_dirs['photon_pv_dir'] = os.path.join(pv_log_dirs['rootdir'], 'photonPVs')
	pv_log_dirs['lcls_pv_dir'] = os.path.join(pv_log_dirs['rootdir'], 'lclsPVs')
	pv_log_dirs['facet_pv_dir'] = os.path.join(pv_log_dirs['rootdir'], 'facetPVs')
	pv_log_dirs['waveform_pv_dir'] = os.path.join(pv_log_dirs['rootdir'], 'waveformPVs')
	pv_log_dirs['unarchived_pv_dir'] = os.path.join(pv_log_dirs['rootdir'], 'unarchivedPVs')

	for dir in pv_log_dirs.keys():
		if not os.path.exists(pv_log_dirs[dir]):
			print 'initializing {}'.format(pv_log_dirs[dir])
			try:
				os.makedirs(pv_log_dirs[dir])
			except OSError as e:	
				print 'Error creating PV log directory: {}'.format(e.message)
		
	return pv_log_dirs

def CyclePVLogFiles(pvfile, dst, keepinputfile=False):
	try:
		if os.path.exists(dst):
			print 'Cycling previous log file {} to {}.old'.format(dst, dst)
			os.system('mv {} {}'.format(dst, dst + '.old'))
	
		if keepinputfile:
			print 'Copying {} to {}'.format(pvfile, dst)
			shutil.copy2(pvfile, dst)			
		else:
			print 'Moving {} to {}'.format(pvfile, dst)
	   		os.system('mv {} {}'.format(pvfile, dst))
	except OSError as e:
		print 'Error cycling PV log file: {}'.format(e.message)

def EmailPVList(smtp, pvlist, email_list, archiver):
	status = 0
	from email.mime.text import MIMEText
	
	from_email = 'controls-system-admins@slac.stanford.edu'
	cc_emails = 'controls-system-admins@slac.stanford.edu'
	to_emails = email_list.split(',')
	to_emails = ', '.join(to_emails)
	
	email_text = 'The following PVs were requested to be added to the ' + archiver + ' Archiver by ACR OPS:\n\n'

	# for Photon PVs, send the host IP address as well
	if archiver == 'Photon':
		email_text += '{0:<60} {1:>4}'.format('PV', 'HOST IP\n')
		email_text += '{0:<60} {1:>4}'.format(''.ljust(60,'-'), ''.rjust(4,'-'))
		email_text += '\n'
		
		pv_rows = ['%s %s\n' % (pv,pvlist[pv]) for pv in pvlist]
		email_text += '\n'.join(('{0:<60} {1:>4}'.format(*row.split())) for row in pv_rows)
	else:
		email_text += ''.join(['%s\n' % pv for pv in pvlist])
	email_text += '\nFor questions or concerns regarding this email, contact Patrick Pascual via:\nPhone: x3539\nEmail: ppascual@slac.stanford.edu'

	pv_email = MIMEText(email_text)
	pv_email['Subject'] = 'PVs requested to be archived {}'.format(date.today())
	pv_email['From'] = from_email
	pv_email['To'] = to_emails
	pv_email['Cc'] = cc_emails
	
	print 'Attempting to send to {} through host {}'.format(to_emails, smtp)


	smtp_host = smtp
	smtp_server = None
	try:
		smtp_server = smtplib.SMTP(smtp_host) # establish SMTP connection using local SMTP host (in PROD)
		smtp_server.sendmail(pv_email['From'], pv_email['To'], pv_email.as_string()) 
		print 'Emailing to: {}'.format(to_emails)
		print 'Cc\'d to: {}'.format(pv_email['Cc'])
		return status
	except smtplib.socket.gaierror as e:
		status = 1
		print 'Error: Could not contact host {}'.format(smtp_host)
	except smtplib.SMTPConnectError as e:
		status = 1
		print 'Error: SMTP connection failed: {}'.format(e.message)
	except smtplib.SMTPAuthenticationError as e:
		status = 1
		print 'Error: SMTP authentication failed: {}'.format(e.message)
	except smtplib.SMTPException as e:
		status = 1
		print 'Error sending email: SMTPError code: {} - {}'.format(e.smtp_code, e.smtp_error)
	finally:
		if smtp_server != None:
			smtp_server.quit() # close SMTP connection

	return status

#def ArchivePVs(pvlist):
#	url = 'http://lcls-archapp.slac.stanford.edu/mgmt/bpl/archivePV'
#	pvs = ','.join(pvlist)

def main():

	# set default input PV file
	default_inputfile = '/u1/lcls/tools/ArchiveBrowser/toBeArchivedList'

	# set default email lists
	default_photon_email = 'bhill@slac.stanford.edu,mcbrowne@slac.stanford.edu'
	default_lcls_email = 'controls-system-admins@slac.stanford.edu'
	default_facet_email = 'controls-system-admins@slac.stanford.edu'

	# set default log directory
	default_logdir = '/u1/lcls/tools/ArchiveBrowser'

	# process command line arguments
	parser = argparse.ArgumentParser(prog='process_toBeArchivedList', description='Processes an input list of PVs and filters them into output lists of Photon Group, LCLS archiver, waveform, and unarchived PVs')
	parser.add_argument('--inputfile', nargs='?', required=False, metavar='filename', default=default_inputfile, help='path to file containing list of PVs to be processed (default: /u1/lcls/tools/ArchiveBrowser/toBeArchivedList)')
	parser.add_argument('--keepinputfile', required=False, action='store_true', help='Flag to determine whether to save the input PV list. (default: Move input PV list to [logdir]/unprocessedPVs directory and rename to toBeArchivedList)')
	parser.add_argument('--photonemail', nargs='?', required=False, metavar='emailaddr1,...', default=default_photon_email, help='Email address(es) to send list of Photon PVs to be archived (comma-separated)')
	parser.add_argument('--nophotonemail', required=False, action='store_true', help='Flag to set whether to send email to Photon Group')	
	parser.add_argument('--lclsemail', nargs='?', required=False, metavar='emailaddr1,...', default=default_lcls_email, help='Email address(es) to send list of LCLS PVs to be archived (comma-separated)')
	parser.add_argument('--nolclsemail', required=False, action='store_true', help='Flag to set whether to send email to LCLS contacts')	
	parser.add_argument('--facetemail', nargs='?', required=False, metavar='emailaddr1,...', default=default_facet_email, help='Email address(es) to send list of FACET PVs to be archived (comma-separated)')
	parser.add_argument('--nofacetemail', required=False, action='store_true', help='Flag to set whether to send email to FACET contacts')	
	parser.add_argument('--logdir', nargs='?', required=False, metavar='path', default=default_logdir, help='root directory for log files (default: /u1/lcls/tools/ArchiveBrowser)')
	parser.add_argument('--smtp', nargs='?', required=False, metavar='hostname', default='localhost', help='Specify the SMTP mail server hostname')
	
	args = parser.parse_args()

	# re-initialize PV log directories if overridden by command line argument --logdir
	pv_log_dirs = InitPVLogs(args.logdir)

	# set PV log file names
	inputlist_file = os.path.join(pv_log_dirs['unprocessed_pv_dir'], 'toBeArchivedList')
	photonlist_file = os.path.join(pv_log_dirs['photon_pv_dir'], 'photon_pv.list')
	lclslist_file = os.path.join(pv_log_dirs['lcls_pv_dir'], 'lcls_pv.list')
	facetlist_file = os.path.join(pv_log_dirs['facet_pv_dir'], 'facet_pv.list')
	waveformlist_file = os.path.join(pv_log_dirs['waveform_pv_dir'], 'waveform_pv.list')
	unarchivedlist_file = os.path.join(pv_log_dirs['unarchived_pv_dir'], 'unarchived_pv.list')

	print 'inputfile = {}'.format(args.inputfile)
	print 'photonemail = {}'.format(args.photonemail)
	print 'nophotonemail = {}'.format(args.nophotonemail)
	print 'lclsemail = {}'.format(args.lclsemail)
	print 'nolclsemail = {}'.format(args.nolclsemail)
	print 'facetemail = {}'.format(args.facetemail)
	print 'nofacetemail = {}'.format(args.nofacetemail)
	print 'smtp = {}'.format(args.smtp)
	print 'logdir = {}'.format(args.logdir)
	print 'photonlist = {}'.format(photonlist_file)
	print 'lclslist = {}'.format(lclslist_file)
	print 'facetlist = {}'.format(facetlist_file)
	print 'waveformlist = {}'.format(waveformlist_file)
	print 'unarchivedlist = {}'.format(unarchivedlist_file)

	blank = re.compile('^[\s]*$')
	timestamp = re.compile('^[\d]{2}-[A-Z][a-z]{2}-[\d]+ [\d]{2}:[\d]{2}:[\d]{2} ') # strip timestamp

	pvlist = []

	with open(args.inputfile, 'r') as f:
		for pvstring in f:
			if blank.match(pvstring):
				continue
			else:
				try:
					if timestamp.match(pvstring):
						ts = timestamp.match(pvstring)
						pv = pvstring[ts.end():len(pvstring)]
						pvlist.append(string.rstrip(pv))
				except ValidationError as e:
					print 'Error: {}'.format(e.value)
					exit(1)

	# clear PV list of duplicates
	pvlist = list(set(pvlist))

	# get Channel Access info 			
	from epics import cainfo

	cainfo_start = re.compile('^==.*==$')
	pv_attr_delim = re.compile('[\s]+=[\s]+')
	lcls_ip_range = re.compile('172\.27\.[0-3]\.')
	facet_ip_range = re.compile('172\.27\.7[2-5]\.')
	mcc_ip_range = re.compile('134.79.151.11')
	lcls_pvlist = []
	facet_pvlist = []
	photon_pvlist = {}
	waveform_pvlist = []
	unarchived_pvlist = [] 


	for pv in pvlist: # save Channel Access information in dictionary as key:value pairs
		print 'processing pv {}'.format(pv)
		pv_attr_dict = {}
		try:
			pv_attrs = cainfo(pv, False)
			if pv_attrs != None:
				pv_attr_list = pv_attrs.splitlines()
				for attr in pv_attr_list:
					if cainfo_start.match(attr) != None: # skip first line of epics.cainfo() output
						continue
					else:
						pv_attr_delim_found = pv_attr_delim.search(attr) # "key<tab>= value" as delimiter
						if pv_attr_delim_found != None:
							pv_attr_key = string.strip(attr[0:pv_attr_delim_found.start()])
							pv_attr_val = string.strip(attr[pv_attr_delim_found.end():len(attr)])
							pv_attr_dict[pv_attr_key] = pv_attr_val
						else: # skip last line of epics.cainfo() output
							continue

				try:
					# get the host from cainfo
					if 'host' in pv_attr_dict.keys() and pv_attr_dict['host'] != None:
						if pv_attr_dict['host'] != '<disconnected>':
							# ignore waveforms (PVs with > 1 data elements)
							if ('count' in pv_attr_dict.keys() and pv_attr_dict['count'] != None
									and 'nelm' in pv_attr_dict.keys() and pv_attr_dict['nelm'] != None):
								if int(pv_attr_dict['count']) > 1 or int(pv_attr_dict['nelm']) > 1:
									if pv in waveform_pvlist:
										print 'pv {} already in Waveform PV list'.format(pv)
									else:
										print 'adding pv {} to Waveform PV list'.format(pv)
										waveform_pvlist.append(pv) # append to list of waveform PVs
								else:
									# save host from host:port pair
									pv_host = string.split(pv_attr_dict['host'], ':')[0] 
									pv_host_ip = socket.gethostbyname(pv_host)
								
									# filter by PV Gateway IP ranges 
									if lcls_ip_range.match(pv_host_ip) != None:
										if pv in lcls_pvlist:
											print 'pv {} already in LCLS Archiver PV list'.format(pv)
										else:
											print 'adding pv {} to LCLS Archiver PV list'.format(pv)
											lcls_pvlist.append(pv)
									elif facet_ip_range.match(pv_host_ip) != None or mcc_ip_range.match(pv_host_ip):
										if pv in facet_pvlist:
											print 'pv {} already in FACET Archiver PV list'.format(pv)
										else:
											print 'adding pv {} to FACET Archiver PV list'.format(pv)
											facet_pvlist.append(pv)
									else:
										if pv in photon_pvlist:
											print 'pv {} already in Photon PV list'.format(pv)
										else:
											print 'adding pv {} from {} to Photon PV list'.format(pv, pv_host_ip)
											photon_pvlist[pv] = pv_host_ip
							else:
								raise ChannelAccessInfoError('count or nelm undefined for pv {}'.format(pv)) 
						else:
							raise ChannelAccessInfoError('host disconnected for PV {}'.format(pv))
					else:
						raise ChannelAccessInfoError('no host specified for PV {}'.format(pv))

				except ChannelAccessInfoError as e: # handle any Channel Access exceptions
					print 'Error: {}'.format(e.value)
			else:
				print '************* {} unavailable **************'.format(pv)
		except TypeError as e:
			print 'Error retrieving information for PV {}: {}'.format(pv, e.message)
			print '************* {} unavailable **************'.format(pv)
		print '\n'

	# save remaining PVs to unarchived list, if any
	# use sets to determine what PVs were successfully processed above
	pv_set = set(pvlist)
	photon_set = set(photon_pvlist.keys())
	lcls_set = set(lcls_pvlist)
	facet_set = set(facet_pvlist)
	waveform_set = set(waveform_pvlist)

	unarchived_pvlist = list(pv_set.difference(waveform_set, photon_set, lcls_set, facet_set))

	print '\n'
	print '{} has {} elements'.format(unarchivedlist_file, len(pvlist))
	print '{} has {} elements'.format(photonlist_file, len(photon_pvlist))
	print '{} has {} elements'.format(lclslist_file, len(lcls_pvlist))
	print '{} has {} elements'.format(facetlist_file, len(facet_pvlist))
	print '{} has {} elements'.format(waveformlist_file, len(waveform_pvlist))
	print '{} has {} elements'.format(unarchivedlist_file, len(unarchived_pvlist))


	# save found waveform PVs in a log file
	with open(waveformlist_file, 'w') as waveform_pvfile:
		for pv in waveform_pvlist:
			print>>waveform_pvfile, '{}'.format(pv)

	
	# save found Photon Group PVs in a log file and email to Photon Group, if any
	if len(photon_pvlist) > 0:
		with open(photonlist_file, 'w') as photon_pvfile:
			for pv in photon_pvlist:
				print>>photon_pvfile, '{}\t\t{}'.format(pv, photon_pvlist[pv])

		if not args.nophotonemail:
			archiver = 'Photon'
			email_status = EmailPVList(args.smtp, photon_pvlist, args.photonemail, archiver) 
			if email_status > 0:
				print 'Error sending PV list'

	# save found LCLS Archiver PVs in a log file and email to LCLS email list, if any
	if len(lcls_pvlist) > 0:
		with open(lclslist_file, 'w') as lcls_pvfile:
			for pv in lcls_pvlist:
				print>>lcls_pvfile, '{}'.format(pv)

		# email LCLS PVs
		if not args.nolclsemail:
			archiver = 'LCLS'
			email_status = EmailPVList(args.smtp, lcls_pvlist, args.lclsemail, archiver)
			if email_status > 0:
				print 'Error sending PV list'

	# save found FACET Archiver PVs in a log file and email to FACET email list, if any
	if len(facet_pvlist) > 0:
		with open(facetlist_file, 'w') as facet_pvfile:
			for pv in facet_pvlist:
				print>>facet_pvfile, '{}'.format(pv)

		# email FACET PVs
		if not args.nofacetemail:
			archiver = 'FACET'
			email_status = EmailPVList(args.smtp, facet_pvlist, args.facetemail, archiver)
			if email_status > 0:
				print 'Error sending PV list'

	# save leftover unarchived PVs in a log file
	with open(unarchivedlist_file, 'w') as unarchived_pvfile:
		for pv in unarchived_pvlist:
			print>>unarchived_pvfile, '{}'.format(pv)

	# move original toBeArchivedList file to unprocessed folder unless 'keepinputfile' flag specified
	toBeArchivedList_dst = os.path.join(pv_log_dirs['unprocessed_pv_dir'], os.path.basename(inputlist_file))
	CyclePVLogFiles(args.inputfile, toBeArchivedList_dst, args.keepinputfile)

# program entry point
if __name__ == '__main__':
	main()
