#!/bin/dash

# Copyright (C) 2023 Futurehome AS
# All rights reserved

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

set -e

has_failed=false

if ! [ "$#" -eq 2 ] > /dev/null
then
  >&2 printf %s\\n "Error: usage: $0 gpio_pin 0|1"
  exit 1
fi

if ! [ "$1" -ge 1 ]
then
  >&2 printf %s\\n "Error: invalid GPIO pin: $1"
  has_failed=true
fi

if ! [ "$1" -le 1023 ]
then
  >&2 printf %s\\n "Error: invalid GPIO pin: $1"
  has_failed=true
fi

if [ "$2" != "0" ] && [ "$2" != "1" ]
then
  >&2 printf %s\\n "Error: invalid GPIO value: $2"
  has_failed=true
fi

if [ "$has_failed" = "true" ]
then
  exit 1
fi

unset -v has_failed

pin_nr="$1"
value="$2"

gpio_dir="/sys/class/gpio"
pin_dir="$gpio_dir/gpio$pin_nr"

export_file="$gpio_dir/export"
direction_file="$pin_dir/direction"
value_file="$pin_dir/value"

if [ ! -d "$pin_dir" ]
then
  if ! printf %s "$pin_nr" | tee "$export_file" > /dev/null
  then
    exit 1
  fi
fi

prev_direction=$(head -n1 "$direction_file")
if [ "$prev_direction" = "out" ]
then
  printf %s "$value" | tee "$value_file" > /dev/null
else
  if [ "$value" = 0 ]
  then
    printf low | tee "$direction_file" > /dev/null
  else
    printf high | tee "$direction_file" > /dev/null
  fi
fi
