#!/usr/bin/env python
'''

@name: add_elog_user.py
@author: Patrick Pascual (ppascual@slac.stanford.edu)
@created: 07/16/2015

@description: Script to add a new Operations E-Log user to the database.

'''

import argparse
import elogutils
import os
import shlex
import subprocess

def main():

	restricted_logbooks = elogutils.get_restricted_logbooks()
	restricted_help_str = 'Comma-separated list of restricted logbooks to provide access to. Current restricted logbooks: ' + ', '.join([lb for lb in restricted_logbooks]) + ' (Default: No restricted logbook access)'

	parser = argparse.ArgumentParser(prog='add_elog_user', description='Adds an Operations E-Log user to the database and allows write access to the specified logbooks')
	parser.add_argument('username', metavar='username', help='The Unix username of the person to be added to the Operations E-Log authorized user list')
	parser.add_argument('--firstname', required=False, nargs='+', metavar='name', help='The first name of the user to be added to the Operations E-log authorized user list')
	parser.add_argument('--lastname', required=False, nargs='+', metavar='name', help='The last name of the user to be added to the Operations E-log authorized user list')
	parser.add_argument('--restrictedaccess', nargs='?', metavar='logbook1,...', required=False, help=restricted_help_str)

	args = parser.parse_args()

	try: # check if Unix user account exists
		ypcat_cmd_str = 'ypcat passwd' 
		ypcat_cmd_args = shlex.split(ypcat_cmd_str)
		grep_cmd_str = 'grep {}'.format(args.username)
		grep_cmd_args = shlex.split(grep_cmd_str)
		ypcat = subprocess.Popen(ypcat_cmd_args, stdout=subprocess.PIPE)
		user_info = subprocess.check_output(grep_cmd_args, stdin=ypcat.stdout)

		user_info = user_info.strip()
		passwd_dict = {}
		passwd_keys = ('username', 'password', 'user_id', 'group_id', 'user_info', 'home_dir', 'cmd')
		passwd_vals = user_info.split(':')
		for key, val in zip(passwd_keys,passwd_vals):
			passwd_dict[key] = val

		print passwd_dict

		# get first name and last name from passwd file to use if not passed in as arguments
		passwd_fullname = passwd_dict['user_info'].split()
		passwd_fname = passwd_fullname[0]
		passwd_lname = passwd_fullname[-1]

		firstname_str = ''
		if args.firstname is not None:
			firstname_str = ' '.join([str(name) for name in args.firstname])
		else:
			firstname_str = passwd_fname # default to name specified in passwd file

		lastname_str = ''
		if args.lastname is not None:
			lastname_str = ' '.join([str(name) for name in args.lastname])
		else:
			lastname_str = passwd_lname # default to name specified in passwd file

		print 'first:\'{}\' last:\'{}\''.format(firstname_str, lastname_str)

		restricted_list = []
		if args.restrictedaccess is not None:
			restricted_list = args.restrictedaccess.split(',')
		print 'restricted access: {}'.format(restricted_list)

		status = elogutils.insert_elog_user(args.username, firstname_str, lastname_str, restricted_list)	
		if status == 1:
			exit(1)	
				
	except subprocess.CalledProcessError as e:
		if e.cmd[0] == 'grep' and e.returncode == 1:
			print 'No Unix account found for username {}'.format(args.username)
		else:
			cmd_str = ' '.join(e.cmd)
			print 'Process \'{}\' returned exit code {}: {}'.format(cmd_str, e.returncode, e.output)

if __name__ == '__main__':
	main()

