#!/usr/bin/env python3
"""
#
# PROFIBUS - GSD file parser
#
# Copyright (c) 2016 Michael Buesch <m@bues.ch>
#
# Licensed under the terms of the GNU General Public License version 2,
# or (at your option) any later version.
#
"""

from __future__ import division, absolute_import, print_function, unicode_literals

import sys
from pyprofibus.gsd.interp import GsdInterp, GsdError

import sys
import getopt


def usage():
	print("GSD file parser")
	print("")
	print("Usage: gsdparser [OPTIONS] [ACTIONS] FILE.GSD")
	print("")
	print("FILE.GSD is the GSD file to parse.")
	print("")
	print("Options:")
	print(" -d|--debug          Enable parser debugging (default off)")
	print(" -h|--help           Show this help.")
	print("")
	print("Actions:")
	print(" -S|--summary        Print a summary of the GSD file contents.")
	print("                     (The default, if no action is specified)")

def main():
	opt_debug = False
	actions = []

	try:
		(opts, args) = getopt.getopt(sys.argv[1:],
			"hdS",
			[ "help",
			  "debug",
			  "summary", ])
	except getopt.GetoptError as e:
		sys.stderr.write(str(e) + "\n")
		usage()
		return 1
	for (o, v) in opts:
		if o in ("-h", "--help"):
			usage()
			return 0
		if o in ("-d", "--debug"):
			opt_debug = True
		if o in ("-S", "--summary"):
			actions.append("summary")
	if len(args) != 1:
		usage()
		return 1
	gsdFile = args[0]
	if not actions:
		actions = [ "summary", ]

	try:
		interp = GsdInterp.fromFile(gsdFile, debug = opt_debug)
		for action in actions:
			if action == "summary":
				print(str(interp))
			else:
				assert(0)
	except GsdError as e:
		sys.stderr.write("ERROR: %s\n" % str(e))
		return 1
	except Exception as e:
		sys.stderr.write("Exception: %s\n" % str(e))
		return 1
	return 0

if __name__ == "__main__":
	sys.exit(main())
