#!/usr/bin/python
# PYTHON_ARGCOMPLETE_OK
#
# Copyright 2020 Cumulus Networks, Inc.
# Author: Ashwini Reddy, ashred@cumulusnetworks.com
#
# The tool loads the config from the file provided to the load argument.
# e.g: -load /etc/cumulus/switchd.d/port-mirror.conf
#
# Prefix argument is optional. The tool processes all lines that start with the prefix
# provided. Comments are ignored by default.
# e.g: -prefix mirror

try:
	import os
	import re
	import argparse
	import logging
	import subprocess
	import sys
except ImportError, e:
	raise ImportError (str(e) + "- required module not found")

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--load', action='store',
                    dest='file',
                    help='Path to the config file.')
parser.add_argument('-prefix', action='store',
		    dest='prefix',
		    help='Prefix of config lines to execute.')
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
		    help="switchdctl tool loads the\n"
                    "/etc/cumulus/switchd.d/*.conf file provided switchd supports\n"
                    "loading of these parameters in the file in runtime and do not need switchd restart.")
try:
	results = parser.parse_args()
except IOError, e:
	logging.error('Arg parsing failed')
	exit(1)

isPathPresent = os.path.isfile(results.file.rstrip('\r\n'))
if not isPathPresent:
        exit(0)
try:
	f = open(results.file.rstrip('\r\n'),'r')
except OSError, e:
	logging.info('Failed to open file %s errror %s', results.file, str(e))
	exit(0)
for line in f:
	sfs_path = "/cumulus/switchd/config/"
	if results.prefix:
		if line.startswith(results.prefix.strip()) == 0:
			continue;
	if len(line) == 0 or line.startswith('#') or line.startswith('\n'):
		continue;
	if line:
		key, value = line.split('=')
	if key:
		words = key.split('.')
		num = len(words)
		for word in words:
			sfs_path += word
			if (num != 1):
				sfs_path += '/'
			num = num - 1
	val_str = value.rstrip('\r\n')
	try:
		os.path.isfile(sfs_path)
	except OSError, e:
		logging.error('sfs path does not exist')
		exit(1)
	exec_cmd = "{0} {1} {2} {3}".format("echo", val_str, '>', sfs_path)
	try:
		res= subprocess.Popen(exec_cmd, stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT)
		output,error = res.communicate()
		if output:
			logging.error(output)
			exit(1)
		if error:
			logging.error(error)
			exit(1)
	except IOError, e:
		logging.error('Command failed')
		exit(1)
	except OSError as e:
		logging.errror('Os error')
		exit(1)
	except:
		logging.error('sys error')
		exit(1)
