#!/bin/bash
function usage {
echo "
  Resets the PIOP of a given DUPCD (Klys or Sbst) given device-type, 
  area (aka branch) and unit number. 
 
  -t <Klys-device-type>. Must be KLYS or SBST, eg -t klys
  -b <CAMAC-branch-name> eg -b LI28
  -u <Klys-device-unit>. Klystron device unit number, eg -u 11

  Usage:
         piopreset [-h] -t {SBST|KLYS} -b area -u unit
 
  E.g.
         piopreset -t klys -b li18 -u 61     Resets PIOP of KLYS:LI18:11
         piopreset -h                        Prints this help

  Exit conditions
  0 - normal successful completion
  1 - too few arguments
  2 - exited after user abort

  Ver. 1.0
"
}
#!---------------------------------------------------------
#! Auth: Greg White, 08-Jan-2011
#! Rev:  Mike Zelazny, 10-Lan-2011
#!---------------------------------------------------------
#! Mod:  Greg White, 05-May-2011
#!       Fix condition handling from ploc. 
#!       Greg White, 06-May-2001
#!       Added a=0 to camcom, but pretty sure it's not required.
#! ========================================================

type=
br=
unit=
cr=
mo=
while getopts b:t:u:h opt
do
   case "$opt" in
      h) usage; exit 0;;
      t) type=`echo $OPTARG | tr '[:lower:]' '[:upper:]'`;;
      b) br=`echo $OPTARG | tr '[:lower:]' '[:upper:]'`;;
      u) unit=$OPTARG;;
      *) echo "Unknown argument, see ploc -h"; exit 1;;
   esac
done
shift $((OPTIND-1))

# Check for insufficient arguments.
if [ -z "$type" ] || [ -z "$br" ] || [ -z "$unit" ]; then
   echo "Too few arguments, see $basename -h for help.";
   exit 1;
fi

#! Confirm
read -p "Resetting crashes PIOP. ARE YOU SURE? (Press 'y' continue, any other to quit)" \
-n 1 -s confirm
echo

if [[ $confirm != y* ]] && [[ $confirm != Y* ]]; then
   echo "Quiting PIOP reset at users request"
   exit 2;
fi

# Find the crate and module of the device given
crateandmod="`$LCLS_ROOT/tools/script/ploc -q $type $br $unit`"
stat=$?
if [ $stat != 0 ]; then
   echo "Error getting Crate and Module information from PLOC, exiting"
   exit $stat
fi 
cr=`echo $crateandmod | cut -d" " -f 1`
mo=`echo $crateandmod | cut -d" " -f 2`
echo br = "$br", cr = "$cr", mo = "$mo"

#! Ok, now do the CAMCOM 
#!
/usr/local/lcls/epics/extensions/extensions-R3-14-8-2/bin/linux-x86/caCamcom <<EOF 
set/branch=$br/cr=$cr/mo=$mo
doit/f=25/a=0
show
exit
EOF

#!if [ $? == 0 ]; then
#!   echo "PIOP reset $br $cr $mo $f, completed successfully"
#!else
#!   echo "PIOP reset $br $cr $mo $f, completed *with error(s)*"
#!fi



 
