#!/bin/csh -f

#
# reconfigure the configuration ROMs.
#
# erase and then write a .rpd file for each FPGA's ROM.
#

set cmdname  = $0:t;
set rootpath = $0:h/../..
pushd $rootpath > /dev/null
set rootpath = `pwd`
popd > /dev/null

if ( $#argv < 1 ) then
cat << DESC_END
reconfigure the configuration ROM(s) of GRAPE-9 FPGA(s).
  usage: $cmdname <.rpd file> [device IDs]
     ex) $cmdname g5pipe.rpd 0 1 2 3

  reconfigure all ROM(s) listed in the GDEVICE environment variable,
  if device IDs are not given. recongifure all ROM(s) of all devices,
  if GDEVICE is not set.
DESC_END
    exit;
endif

set rpdfile = $argv[1];

if (! -f ${rpdfile}) then
  echo "file ${rpdfile} not found."
  exit 1
endif

# set all valid device IDs to ids.
set ids = ( `${rootpath}/hibutil/lsgrape | grep GRAPE-9 | awk '$1 ~ /[0-9]+/{printf($1 " ");}'` )
set ndev = ${#ids}

# overwrite ids if GDEVICE is set or argv is given.
if ( $#argv < 2 ) then
  if ( $?GDEVICE ) then
    echo "GDEVICE='$GDEVICE'"
    set ids = ( $GDEVICE )
  endif
else
  shift argv
  set ids = ( $argv )
endif

if ( $#ids < 1) then
  echo "no device found to be reconfigured."
  exit
endif

cat << STARTMSG_END

Going to reconfigure the ROM(s) of the following $#ids device(s)

  device ID(s) : $ids
with RPD file  : ${rpdfile}.

The reconfiguration takes a few minutes, and you must not power off
the devices until the reconfiguration completes.

STARTMSG_END

echo -n "Are you ready? (y/n) : "


LABEL_RETRY:
set answer = $<
if ( $answer == "n") then
  echo "The reconfiguration canceled."
  exit 1
else if ( $answer != "y") then
  echo ''
  echo "Answer with 'y' or 'n'."
  echo ''
  goto LABEL_RETRY
endif

echo "Start the reconfiguration..."

while (0 < $#ids)
    set devid = $ids[1];
    if ($devid < 0) then
        echo "Too small FPGA ID:$devid. Abort."
        exit 1
    endif
    if ($devid >= $ndev) then
        echo "Too large FPGA ID:$devid. Abort."
        exit 1
    endif

    (\
      echo rpdfile:${rpdfile}    devid:${devid};\
      ${rootpath}/hibutil/hibtest 19 ${devid};\
      ${rootpath}/hibutil/hibtest 20 ${rpdfile} ${devid};\
      ${rootpath}/hibutil/hibtest 27 ${devid};\
    )&
    shift ids
end

# wait until all sub programs are done.
set nruns = 1
while (${nruns} > 0)
  set nruns = `ps x | pgrep hibtest | wc -l`
  sleep 1
end

echo ""
echo "All devices reconfigured successfully."
echo ""

exit 0
