#!/bin/bash
##########################################################################
# CPRUPS Daemon v0.2
##########################################################################
# Copy this bash script into this file: /home/robot/utils/cprups
# Script to
#       - send boot complete (LO) / shutdown complete (HI) on GPIO pin
#
# Commonplace Robotics GmbH 2021-09-02
# Author PL
#
# v0.2: no shutdown, only boot complete pin
##########################################################################



##########################################################################
# Example systemd script 
##########################################################################
# To start cprups as daemon on boot, copy the following lines into 
# this file: /etc/systemd/system/cprupsd.service and
# $ systemctl enable cprupsd
# $ systemctl start cprupsd
# $ reboot
##########################################################################
# [Unit]
# Description=A demon to communicate with Commonplace Robotics UPSes
# After=network.target auditd.service
#
# [Service]
# ExecStart=/home/robot/utils/cprups
# ExecReload=/bin/kill -HUP $MAINPID
# KillMode=process
# Restart=on-failure
# RestartPreventExitStatus=255
# Type=notify
#
# [Install]
# WantedBy=multi-user.target
# Alias=cprupsd.service
############################################################################



#Define GPIO Pins

bootCompletePin="6"             # GPIO number of the transmit pin to report:
                                # booting (HI)
                                # succesful boot (LO)
                                # shutdown complete (HI).


# Note that this script does not need to run fast,
# if the hardware works as intended.

longDelay="0.5s"                # sleep for above 200ms.
shortDelay="0.2s"               # sleep for below 500ms
bootCompletePinValue="0"        # report boot complete as LO.



# Unexport GPIOs, in case they are in use (e.g. by a previous instance of this).
# If the two GPIOs specified above are not free, they will be after this:

DIR="/sys/class/gpio/gpio$bootCompletePin"
if [ -d "$DIR" ]; then
  # Take action if $DIR exists. #
  echo "cprupsd: Unexporting (cleaning up) GPIO$bootCompletePin"
  echo $bootCompletePin > /sys/class/gpio/unexport
  sleep $longDelay
fi



# make bash safe
# -e: exit the script, if a command fails
# -o pipefail: exit when a pipe fails
# systemd will reload the script and try again... I assume. NDCK

set -eo pipefail


# Export GPIOs

echo "cprupsd: Exporting bootCompletePin GPIO$bootCompletePin"
echo "$bootCompletePin" > /sys/class/gpio/export
sleep $longDelay
