#!/bin/sh

##############################################################################
#
# GPIO setup script for SvxLink server. Run this script to set up the GPIO
# configuration specified in the GPIO specific configuration file
# /etc/svxlink/gpio.conf
#
##############################################################################

GPIO_CONF="/etc/svxlink/gpio.conf"
[ -r "$GPIO_CONF" ] && . "$GPIO_CONF"


# Set up the given GPIO input pin.
# Enable the given GPIO pin, set direction to input and set active state
# (active low or active high). Also set user, group and mode for the pin.
gpio_in_setup()
{
  local PIN="$1"
  local ACTIVE_LEVEL="$2"

  if [ "$ACTIVE_LEVEL" = "low" ]; then
    local ACTIVE_LOW="1"
  else
    local ACTIVE_LOW="0"
  fi

  if [ -n "$PIN" -a ! -e /sys/class/gpio/$PIN ]; then
    # Extract pinnumber from the full pin name (e.g. gpio4_pd0 -> 4)
    local pinnum=$(echo "$PIN" | sed 's/^[^0-9]*\([0-9][0-9]*\).*$/\1/')
    echo $pinnum > $GPIO_PATH/export && \
      echo "in" > $GPIO_PATH/$PIN/direction && \
      echo "$ACTIVE_LOW" > $GPIO_PATH/$PIN/active_low
    [ -n "$GPIO_USER" ] && chown "$GPIO_USER" $GPIO_PATH/$PIN/value
    [ -n "$GPIO_GROUP" ] && chgrp "$GPIO_GROUP" $GPIO_PATH/$PIN/value
    [ -n "$GPIO_MODE" ] && chmod "$GPIO_MODE" $GPIO_PATH/$PIN/value
  fi
}


# Set up the given GPIO output pin.
# Enable the given GPIO pin, set direction to output, set active state (active
# low or active high) and reset to OFF value. Also set user, group and mode for
# the pin.
gpio_out_setup()
{
  local PIN="$1"
  local ACTIVE_LEVEL="$2"

  if [ "$ACTIVE_LEVEL" = "low" ]; then
    local ACTIVE_LOW="1"
  else
    local ACTIVE_LOW="0"
  fi

  if [ -n "$PIN" -a ! -e $GPIO_PATH/$PIN ]; then
    # Extract pinnumber from the full pin name (e.g. gpio4_pd0 -> 4)
    local pinnum=$(echo "$PIN" | sed 's/^[^0-9]*\([0-9][0-9]*\).*$/\1/')
    echo $pinnum > $GPIO_PATH/export && \
      echo "out" > $GPIO_PATH/$PIN/direction && \
      echo "$ACTIVE_LOW" > $GPIO_PATH/$PIN/active_low && \
      echo 0 > $GPIO_PATH/$PIN/value
    [ -n "$GPIO_USER" ] && chown "$GPIO_USER" $GPIO_PATH/$PIN/value
    [ -n "$GPIO_GROUP" ] && chgrp "$GPIO_GROUP" $GPIO_PATH/$PIN/value
    [ -n "$GPIO_MODE" ] && chmod "$GPIO_MODE" $GPIO_PATH/$PIN/value
  fi
}


## Set up GPIO input pins that should be active high
for pin in $GPIO_IN_HIGH; do
  gpio_in_setup "$pin" high
done

## Set up GPIO input pins that should be active low
for pin in $GPIO_IN_LOW; do
  gpio_in_setup "$pin" low
done

## Set up GPIO output pins that should be active high
for pin in $GPIO_OUT_HIGH; do
  gpio_out_setup "$pin" high
done

## Set up GPIO output pins that should be active low
for pin in $GPIO_OUT_LOW; do
  gpio_out_setup "$pin" low
done
