#!/bin/bash

# ****************************************** PARAMETERS *******************************************

ASSETS_DIRECTORY=..
GPIO_SCRIPT=${ASSETS_DIRECTORY}/gpio.sh
PIN_ID=237
ARG=$1

# ******************************************* FUNCTIONS *******************************************

function try_to_stuck() {
    # Commands who can stuck process
    ps aux > /dev/null 2>&1
    dmesg > /dev/null 2>&1
    journalctl > /dev/null 2>&1

    # Wait until no one program are in D state
    while [ -n "$(cat /proc/*/stat 2>/dev/null | awk '{if ($3=="D") print $1, $2, $3, $NF}')" ]; do
      sleep 0.5
    done
}

# ********************************************* MAIN **********************************************

if [ "$EUID" -ne 0 ]; then
    error "Please run as root."
    exit 1
fi

if [ ! -f "$GPIO_SCRIPT" ]; then
    error "Unable to found gpio script ($GPIO_SCRIPT)."
    exit 2
fi

if [ "$ARG" != "--no-init" ]; then
  $GPIO_SCRIPT $PIN_ID init
fi
$GPIO_SCRIPT $PIN_ID out

while true
do
    try_to_stuck
    $GPIO_SCRIPT $PIN_ID toggle
    sleep 0.5
done