#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# TTTech Nerve LED GPIO
# Copyright(c) 2021 TTTech Industrial Automation AG.
#
# ALL RIGHTS RESERVED.
# Usage of this software, including source code, netlists, documentation,
# is subject to restrictions and conditions of the applicable license
# agreement with TTTech Industrial Automation AG or its affiliates.
#
# All trademarks used are the property of their respective owners.
#
# TTTech Industrial Automation AG and its affiliates do not assume any liability
# arising out of the application or use of any product described or shown
# herein. TTTech Industrial Automation AG and its affiliates reserve the right to
# make changes, at any time, in order to improve reliability, function or
# design.
#
# Contact Information:
# support@tttech-industrial.com
# TTTech Industrial Automation AG, Schoenbrunnerstrasse 7, 1040 Vienna, Austria

import argparse
import glob
import os


parser = argparse.ArgumentParser(description='Enable/Disable GPIO interface for LEDs.')
parser.add_argument('action', default='enable', choices=['enable', 'disable', ], nargs='?',
                    help="Wether to enable or disable GPIOs. Default action is %(default)s.")
args = parser.parse_args()


def gpios():
    for dirname in glob.glob('/sys/class/gpio/gpiochip*'):
        with open(os.path.join(dirname, 'label')) as stream:
            label = stream.read().strip()
        if label not in ['de01-pio-out', 'de01-pio-int-in', ]:
            continue

        with open(os.path.join(dirname, 'base')) as stream:
            first = int(stream.read().strip())
        with open(os.path.join(dirname, 'ngpio')) as stream:
            count = int(stream.read().strip())

        for i in range(first, first + count):
            yield i


if args.action == 'enable':
    for gpio in gpios():
        try:
            with open('/sys/class/gpio/export', 'w') as stream:
                stream.write(str(gpio))
        except (OSError, IOError) as e:
            print('Warning: Could not enable GPIO %s: %s ' % (gpio, e))

    # enable button
    try:
        with open('/sys/class/gpio/function-button/edge', 'w') as stream:
            stream.write('both')
    except (OSError, IOError) as e:
        print('Warning: Could not enable function button.')
else:  # disable
    for gpio in gpios():
        with open('/sys/class/gpio/unexport', 'w') as stream:
            stream.write(str(gpio))
