#!/bin/sh
#
#  SELF_UPDATE - Update the update scripts.

set -e

# Initialize the $iraf and environment.
if [ -z "$iraf" ]; then
  if [ -e "$HOME/.iraf/setup.sh" ]; then
    . "$HOME/.iraf/setup.sh"
  else
    . unix/hlib/setup.sh
  fi
else
    . "$iraf/unix/hlib/setup.sh"
fi

. $iraf/unix/hlib/irafuser.sh

cd "$iraf/util"

REPO=$("${iraf}/util/pkgrepo")

printf "Updating utility scripts ...."

# Delete any existing downloads.
if [ -e /tmp/util.tgz ]; then
    rm -f /tmp/util.tgz
fi

# Get the latest script distribution.
./fget -o /tmp/util.tgz "${REPO}/util-universal.tar.gz"

# Go to iraf root, unpack and clean up.  Using the IRAF root gives us
# the chance to update the toplevel Makefile or other build scripts in
# the system, e.g. in the 'vendor' directory.
(cd ../ && tar zxf /tmp/util.tgz && rm -f /tmp/util.tgz )

# Edit the current IRAF path into the scripts.
cd "$iraf/unix/hlib"
pfiles="cl.sh cl.csh ecl.sh ecl.csh vocl.sh vocl.csh setup.sh setup.csh mkiraf.sh mkiraf.csh"
d_iraf="/iraf/iraf/"

for file in $pfiles; do
    sed -e "s+$d_iraf+$iraf+" -i "$file"
done
cd "$iraf"
echo "Done"

exit 0
