#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# TTTech Nerve production tests
# Copyright(c) 2018 TTTech Computertechnik AG.
#
# For software distribution license terms see LICENSE for details.
#
# Contact Information:
# support@tttech.com
# TTTech Computertechnik 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))
