#!/bin/sh
#
#  IRAF_LATEST - Update the system with the latest distribution files.


opt="all"


if [ $# -lt 1 ]; then
    echo "Usage:  iraf_latest <opt>"
    exit 0
else
    opt=$1
fi

# 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


# Called from Makefile, set iraf root.
if [ -e "$iraf/unix/hlib/irafuser.sh" ]; then
    . "$iraf/unix/hlib/irafuser.sh"
fi

echo '$iraf is '$iraf


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

#echo "iraf_latest: cwd = " `pwd`

# Figure out which binaries are required.
files="patch-src.tar.gz"			# always need the source ....
bins=""
archs="linux linux64 macosx macintel"
for b in $archs ; do
    if [ -e "bin.$b/x_images.e" ]; then
	bins="$bins $b"
	case "$b" in
	"linux")
	    files="$files patch.lnux.x86.tar.gz"
	    ;;
	"linux64")
	    files="$files patch.lnux.x86_64.tar.gz"
	    ;;
	"macosx")
	    files="$files patch.macx.x86.tar.gz"
	    ;;
	"macintel")
	    files="$files patch.macx.x86_64.tar.gz"
	    ;;
	esac
    fi
done
echo "Updating binaries:  $bins"


# Download the needed files to /tmp

FGET="${iraf}/util/fget"
REPO=$("${iraf}/util/pkgrepo")
for f in $files ; do
    echo "Downloading: $f"
    ${FGET} -q -d /tmp/ "$REPO/$f"

    if [ ! -s "/tmp/$f" ]; then
	echo "Error downloading $REPO/$f, quitting"
	exit 1
    fi

    printf "Unpacking ..."
    tar zxf "/tmp/$f"
    rm -f "/tmp/$f"

    echo    " Done."
done


#  For the initial release, the update procedures haven't yet been defined.
#  This script will be replaced by the working version at the first release.


if [ "$opt" = "all" ]; then			# Update everything
  if [ -e extern/.installed ]; then
    echo "Update all external packages ..."
    (cd extern && make update)
  fi
else
    echo "Unknown option '$opt'"
    exit 1
fi

echo
exit 0
