#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# PiLC HAT configuration tool
#
# Copyright 2016 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from __future__ import division, absolute_import, print_function, unicode_literals

from libpilc.raspi_hat_conf import PilcConf
from libpilc.util import str2bool

import re
import sys
import getopt


def usage():
	print("PiLC HAT configuration tool")
	print("")
	print("pilc-hat-conf [OPTIONS] <ACTIONS>")
	print("")
	print("Actions:")
	print(" -D|--set-pbtxen-dbg MODE      Enable/disable PB-txen debugging")
	print(" -d|--get-pbtxen-dbg           Get PB-txen debugging value")
	print(" -T|--set-pbtxen-to TIMEOUT    Set PB-txen timeout value")
	print(" -t|--get-pbtxen-to            Get PB-txen timeout value")
	print(" -B|--set-baudrate BAUD        Set PB-txen timeout for baudrate")
	print(" -W|--set-eemu-we BOOL         Set EEPROM emulation write-enable")
	print(" -w|--get-eemu-we              Get EEPROM emulation write-enable")
	print(" -X|--set-xtal-cal VALUE       Set crystal calibration value")
	print(" -x|--get-xtal-cal             Get crystal calibration value")
	print("")
	print("Options:")
	print(" -h|--help                     Show this help")
	print(" -b|--bus BUSADDR              Use bus address. Default: 0x%02X" %\
	      PilcConf.DEFAULT_BUS)
	print(" -e|--dev DEVADDR              Use device address. Default: 0x%02X" %\
	      PilcConf.DEFAULT_DEV)

def main():
	opt_bus = PilcConf.DEFAULT_BUS
	opt_dev = PilcConf.DEFAULT_DEV
	actions = []

	try:
		(opts, args) = getopt.getopt(sys.argv[1:],
			"hD:dT:tB:W:wX:xb:e:",
			[ "help",
			  "set-pbtxen-dbg=",
			  "get-pbtxen-dbg",
			  "set-pbtxen-to=",
			  "get-pbtxen-to",
			  "set-baudrate=",
			  "set-eemu-we=",
			  "get-eemu-we",
			  "set-xtal-cal=",
			  "get-xtal-cal",
			  "bus=",
			  "dev=", ])
	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", "--set-pbtxen-dbg"):
			actions.append( ("set-pbtxen-dbg", v.upper().strip()) )
		if o in ("-d", "--get-pbtxen-dbg"):
			actions.append( ("get-pbtxen-dbg", None) )
		if o in ("-T", "--set-pbtxen-to"):
			try:
				v = int(v)
				if v < 0 or v > 0xFFFF:
					raise ValueError
			except ValueError:
				sys.stderr.write("ERROR: Invalid PB timeout value\n")
				return 1
			actions.append( ("set-pbtxen-to", v) )
		if o in ("-t", "--get-pbtxen-to"):
			actions.append( ("get-pbtxen-to", None) )
		if o in ("-B", "--set-baudrate"):
			try:
				v = v.lower().strip()
				fact = 1
				m = re.match(r'^([\d\.]+)\s*((k)|(kbaud)|(kbit))$', v)
				if m:
					v = m.group(1)
					fact = 1000
				m = re.match(r'^([\d\.]+)\s*((m)|(mbaud)|(mbit))$', v)
				if m:
					v = m.group(1)
					fact = 1000000
				v = float(v) * fact
				actions.append( ("set-baudrate", v) )
			except ValueError:
				sys.stderr.write("ERROR: Invalid PB baudrate value\n")
				return 1
		if o in ("-W", "--set-eemu-we"):
			actions.append( ("set-eemu-we", str2bool(v)) )
		if o in ("-w", "--get-eemu-we"):
			actions.append( ("get-eemu-we", None) )
		if o in ("-X", "--set-xtal-cal"):
			try:
				v = int(v, 0)
				if v < 0 or v > 0xFF:
					raise ValueError
			except ValueError:
				sys.stderr.write("ERROR: Invalid xtalcal value\n")
				return 1
			actions.append( ("set-xtal-cal", v) )
		if o in ("-x", "--get-xtal-cal"):
			actions.append( ("get-xtal-cal", None) )
		if o in ("-b", "--bus"):
			try:
				opt_bus = int(v, 0)
				if opt_bus < 0 or opt_bus > 0xFF:
					raise ValueError
			except ValueError:
				sys.stderr.write("ERROR: Invalid bus address\n")
		if o in ("-e", "--dev"):
			try:
				opt_dev = int(v, 0)
				if opt_dev < 0 or opt_dev > 0x7F:
					raise ValueError
			except ValueError:
				sys.stderr.write("ERROR: Invalid device address\n")
	if args or not actions:
		usage()
		return 1

	try:
		conf = PilcConf(opt_bus, opt_dev)
		for action, value in actions:
			if action == "set-pbtxen-dbg":
				if value in {"0", "OFF"}:
					mode = PilcConf.PBTXEN_DBG_OFF
				elif value in {"1", "RETRIG"}:
					mode = PilcConf.PBTXEN_DBG_RETRIG
				elif value in {"2", "NOTRIG"}:
					mode = PilcConf.PBTXEN_DBG_NOTRIG
				else:
					sys.stderr.write("ERROR: Invalid debug mode\n")
					return 1
				conf.set(conf.CONF_PBTXENDBG, mode)
			elif action == "get-pbtxen-dbg":
				mode = conf.get(conf.CONF_PBTXENDBG)
				if mode == PilcConf.PBTXEN_DBG_OFF:
					print("OFF")
				elif mode == PilcConf.PBTXEN_DBG_RETRIG:
					print("RETRIG")
				elif mode == PilcConf.PBTXEN_DBG_NOTRIG:
					print("NOTRIG")
				else:
					print("Unknown (%d)" % mode)
			elif action == "set-pbtxen-to":
				conf.set(conf.CONF_PBTXENTO, value)
			elif action == "get-pbtxen-to":
				print(conf.get(conf.CONF_PBTXENTO))
			elif action == "set-baudrate":
				conf.setBaudrate(value / 1000.0)
			elif action == "set-eemu-we":
				conf.set(conf.CONF_EEMUWE, value)
			elif action == "get-eemu-we":
				print(conf.get(conf.CONF_EEMUWE))
			elif action == "set-xtal-cal":
				conf.set(conf.CONF_XTALCAL, value)
			elif action == "get-xtal-cal":
				print("0x%02X" % conf.get(conf.CONF_XTALCAL))
			else:
				assert(0)
		conf.close()
	except PilcConf.Error as e:
		sys.stderr.write(str(e) + "\n")
		return 1
	return 0

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