#!/bin/sh 
ipmice=`dirname $0`/ipmice
ipmchk=`dirname $0`/checkArduinoConfig
asschk=`dirname $0`/checkAsserts
if [ ! -f $ipmice ]; then ipmice=$ICEROOT/bin/ipmice ; fi
if [ ! -f $ipmice ]; then 
  echo "CheckArduino could not find ipmice executable"
  exit
fi
echo "Setting state=$1 on all Arduino controlled devIces"
let nax=0 nar=0 nat=0
for i in 0 1 2 3 ; do
if [ -e /dev/ttyACM$i ]; then
 if [ "$1" == "0" ]; then
  stat=`$ipmice status $i`
  if [ "`echo $stat | grep -i ice-ax`"  != "" ]; then $ipmice pwr=0 $i ; fi
  if [ "`echo $stat | grep -i ice-ar`"  != "" ]; then $ipmice pwr=0 $i ; fi
  if [ "`echo $stat | grep -i ice-at`"  != "" ]; then $ipmice pwr=0 $i ; fi
  if [ "`echo $stat | grep -i ice-ioc`" != "" -a -f /tmp/iceos.POWEROFF ] ; then $ipmice power=off $i ; fi # only shut off IOC if POWEROFF
 else
  chmod a+rw /dev/ttyACM$i
  chown root.dialout /dev/ttyACM$i
  stty -F /dev/ttyACM$i cs8 2500000 raw -iexten -echo -echoe
  config=none
  stat=`$ipmice status $i`
  if [ "`echo $stat | grep -i ice-tray`"  != "" ]; then ln -sfn ttyACM$i /dev/icetty-mb  ; $asschk /var/etc/ice-tray.conf $i ; $ipmchk /var/etc/icetray.conf $i ; fi
  if [ "`echo $stat | grep -i ice-spac`"  != "" ]; then ln -sfn ttyACM$i /dev/icetty-mb  ; $asschk /var/etc/ice-spac.conf $i ; fi
  if [ "`echo $stat | grep -i ice-supac`" != "" ]; then ln -sfn ttyACM$i /dev/icetty-mb  ; $asschk /var/etc/ice-spac.conf $i ; fi
  if [ "`echo $stat | grep -i ice-npac`"  != "" ]; then ln -sfn ttyACM$i /dev/icetty-mb  ; $asschk /var/etc/ice-npac.conf $i ; fi
  if [ "`echo $stat | grep -i ice-pod`"   != "" ]; then ln -sfn ttyACM$i /dev/icetty-mb  ; $asschk /var/etc/ice-pod.conf $i  ; fi
  if [ "`echo $stat | grep -i ice-ax`"    != "" ]; then ln -sfn ttyACM$i /dev/icetty-ax  ; $ipmice pwr=1 $i ; ln -sfn ttyACM$i /dev/icetty-ax$nax ; let nax++ ; fi
  if [ "`echo $stat | grep -i ice-ar`"    != "" ]; then ln -sfn ttyACM$i /dev/icetty-ar  ; $ipmice pwr=1 $i ; ln -sfn ttyACM$i /dev/icetty-ar$nar ; let nar++ ; fi
  if [ "`echo $stat | grep -i ice-at`"    != "" ]; then ln -sfn ttyACM$i /dev/icetty-at  ; $ipmice pwr=1 $i ; ln -sfn ttyACM$i /dev/icetty-at$nat ; let nat++ ; fi
  if [ "`echo $stat | grep -i ice-ioc`"   != "" ]; then ln -sfn ttyACM$i /dev/icetty-ioc ; $asschk /var/etc/ice-ioc.conf $i ; $ipmchk /var/etc/iceioc.conf $i ; $ipmice power=on $i ; fi
  if [ "`echo $stat | grep -i ice-xcvr`"  != "" ]; then ln -sfn ttyACM$i /dev/icetty-xcvr ; fi
 fi
fi
done
