#!/bin/tcsh -f

##############################
# Keep this next line in script
# AFNI_RUNME_COOKIE
##############################

cat << EOF

This is going to:
   0. verify that we in AFNI_data6
   1. get an updated DICOM_T1.tgz package
   2. extract it and clean up
   3. download current afni02_to3d.pdf to afni_handouts

starting after 10 second nap...

EOF

sleep 10

set afnisite = https://afni.nimh.nih.gov

set get_file = DICOM_T1.tgz
set datadir = AFNI_data6

# find $datadir or quit
# ('cd ..' is because this script is run in a sub-directory)
cd ..
set cdir = `pwd`

# locate $datadir and enter it
if ( -d $datadir ) then
   echo "-- entering $datadir, ready"
   cd $datadir
else if ( $cdir:t == $datadir ) then
   echo "-- already in $datadir, ready"
else if ( $cdir:h:t == $datadir ) then
   echo "-- 1 under $datadir, going up"
   cd ..
else if ( -d $HOME/$datadir ) then
   echo "-- found $datadir under HOME, going in"
   cd $HOME/$datadir
else
   echo "** cannot find $datadir, please go there and re-run"
   exit
endif

# nuke old copy, if it exists
if ( -f $get_file || -d $get_file:r ) then
   echo "-- removing old $get_file..."
   \rm -fr $get_file $get_file:r
endif

# get fatcat files
echo "-- getting $get_file..."
curl -OfS $afnisite/pub/dist/edu/data/misc/$get_file
if ( $status || ! -f $get_file || -z $get_file ) then
   echo "** failed to get $get_file"
   exit
endif

echo "-- extracting $get_file ..."
tar xfz $get_file

if ( $status || ! -d $get_file:r ) then
   echo "** failed to extract $get_file"
   exit
endif

# get rid of tgz extension
set get_file = $get_file:r
echo "-- have $get_file files, removing tgz package"
\rm $get_file.tgz

# if ../afni_handouts exists, get afni02_to3d.pdf
set hdir = ../afni_handouts
if ( -d $hdir ) then
   set newfile = afni02_to3d.pdf
   echo "-- found afni_handouts at same level"
   echo "   getting updated $newfile ...\n"

   curl -OfS $afnisite/pub/dist/edu/latest/afni_handouts/$newfile
   if ( $status || ! -f $newfile || -z $newfile ) then
      echo "** failed to get $newfile"
      exit
   endif
   echo "-- moving $newfile to $hdir ..."
   \mv $newfile $hdir
endif

echo "\nupdate complete (consider removing tmp.afni.run.command\n"
