#!/bin/busybox sh

[ $(id -u) -eq 0 ] || exit 1
cd /
lockFile=/tmp/StopNickel_lock_file
until ln -s $$ $lockFile 2>/dev/null ; do usleep 10000; done
cntFile=/tmp/StopNickel_Stop_Count

nickelpid=$(pidof nickel)
if [ -z "$nickelpid" ] ; then
  echo "nickel is DEAD" 1>&2
  exit 3
fi

awkscr='$1=="State:"{print $2; exit;}'
state=$(awk "$awkscr" /proc/$nickelpid/status)

pipe2nickel=/tmp/nickel-hardware-status
[ -p $pipe2nickel ] || exit 1
pipeTrash=$pipe2nickel.ignored
[ -f $pipeTrash ] || rm -rf $pipeTrash  # force reg file
:>> $pipeTrash

magicMsg='_#wakeup#nickel#_'

if [ -f $cntFile ] ; then
  read n < $cntFile
else
  n=0
fi
case "$state.${0##*/}" in
T.Stop*)
  n=$((n+1))
  echo $n > $cntFile
  echo "nickel is already stopped($n)"
  rm -f $lockFile
;;
*.Stop*)
  if [ $n -ne 0 ] ; then
    echo "Stop_Count=$n but not stopped."
    exit 1
  fi
  echo 1 > $cntFile
  for p in $(pidof fickel hindenburg) $nickelpid ; do
    kill -STOP $p
  done
  echo 'sent STOP signal to nickel'
  :> $pipeTrash
  # pipecleaner
  sdCard=''
  while : ; do
    while read -r l ; do
      echo "$l"
      case "$l" in
      'sd '*)
        if [ -z "$sdCard" ] ; then
          sdCard="$l"
        else
          sdCard=''
        fi
      ;;
      "$magicMsg")
	[ -n "$sdCard" ] && echo "$sdCard" >> $pipe2nickel &
        kill -CONT $nickelpid
        echo "sent CONT signal to nickel" 1>&2
        exit 0
      ;;
      esac
    done < $pipe2nickel
  done >>$pipeTrash </dev/null &
  rm -f $lockFile
;;
T.Cont*)
  if [ $n -gt 1 ] ; then
    n=$((n-1))
    echo $n > $cntFile
    rm -f $lockFile
    echo "nickel is still stopped($n)"
    exit 0
  fi
  for p in $(pidof fickel hindenburg) ; do
    kill -CONT $p
  done
  usleep 300000  # 300ms
  printf '\n%s\n' "$magicMsg" > $pipe2nickel
  for tm in 0 9 99 999 ; do
    usleep $((tm*1000))
    [ "$(awk "$awkscr" /proc/$nickelpid/status)" = T ] || break
    if [ $tm -ge 999 ] ; then
      echo 'FAIL to wake up nickel BY PIPE'
      fuser -k $pipeTrash
      kill -CONT $nickelpid
    fi
  done
  echo 0 > $cntFile
  rm -f $lockFile
;;
*.Cont*)
  echo "nickel is already running($n)"
  rm -f $lockFile
;;
T.*)
  echo "nickel is STOP($n)"
  rm -f $lockFile
;;
*)
  rm -f $lockFile
  echo "nickel is running"
;;
esac 1>&2

exit

