#!/bin/sh
#
#  PKGINST - Install the named package.

if [ $# -lt 1 ]; then
    exit 0
else
    pkg=$1
fi

bindir=$(dirname "$0")                # get iraf root directory 
irafdir=${bindir%/*}

# 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


REPO=$("${irafdir}/util/pkgrepo")
if [ -n "$IRAFARCH" ]; then
    arch=$IRAFARCH
else
    arch=$("${irafdir}/unix/hlib/irafarch.sh" -actual)
fi

echo "Setting architecture: '$arch' .... "
 

# Get any dependency package names.
deps=$(grep "^$pkg" .repo_desc | awk '{printf("%s\n",$2)}' | sed -e 's/,/ /g')
pkg_dep=""
for d in $deps; do 
   if [ "$d" != "none" ]; then
      echo "Adding dependency '$d' ...."
      pkg_dep="$pkg_dep $d"
   fi
done

# Process the requested package and any dependencies.
dep="$pkg_dep $pkg"
for ip in $dep; do

  pfile=$(grep " $ip " .repo_manifest | grep "${arch} " | head -1 | awk '{printf("%s\n",$4)}')

  if echo "$pfile" | grep -q src.tar.gz ; then
    src_only=1
  else
    src_only=0
  fi

  # Remove an existing package file.
  if [ -e "$pfile" ]; then
    rm -f "$pfile"
  fi

  # Download the repo file and unpack it.
  printf "Installing package '%s' .... " "$ip"
  "${irafdir}/util/pkgget" "${REPO}/$pfile"
  if [ $? -gt 0 ]; then
    echo    " [Error]"
    exit $?
  fi

  if [ -e "$pfile" ]; then

    tar zxf "$pfile"
    rm -f "$pfile"
    echo "$(date +%s)  ${ip}.${arch}" > "$ip/.installed.${arch}"
    echo "$(date +%s)  $ip" > "$ip/.installed"

    if [ "$src_only" -gt 0 ]; then
      echo    " [SOURCE ONLY]"
      echo "$(date +%s)  $ip" > "$ip/.src_only"
    else
      echo    " [OK]"
    fi
  else
    echo    " [Error]"
  fi

  "${irafdir}/util/pkgenv" -init

done

exit 0
