#!/bin/csh -f
#
#  PKGINST - Install the named package.

unalias 	grep sort uniq ls awk

if ($#argv < 1) then
    exit 0
else
    set pkg = $1
endif

set  bindir     = "`dirname $0`"                # get iraf root directory 
set  irafdir    = $bindir:h

set  REPO	= `${irafdir}/util/pkgrepo`
if ($?IRAFARCH) then
    set arch    = $IRAFARCH
else
    set arch    = `${irafdir}/unix/hlib/irafarch.csh -actual`
endif

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

# Get any dependency package names.
set deps=`grep ^$pkg .repo_desc | awk '{printf("%s\n",$2)}' | sed -e 's/,/ /g'`
set pkg_dep = ""
foreach d ( $deps )
   if ("$d" != "none") then
      echo "Adding dependency '$d' ...."
      set pkg_dep = "$pkg_dep $d"
   endif
end

# Make a unique list of package, i.e. remove multiple instances of a package.
#   [Note:  Not used, the manifest should have this already. ]
set list = `echo $pkg_dep $pkg|awk 'BEGIN {RS=" |\n";}{print $1;}'|sort|uniq`

# Process the requested package and any dependencies.
foreach ip ($pkg_dep $pkg)

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

  echo $pfile | grep src.tar.gz  > /dev/null
  if ($status == 0) then
    set src_only = 1
  else
    set src_only = 0
  endif

  # Remove an existing package file.
  if (-e $pfile) then
    /bin/rm -f $pfile
  endif

  # Download the repo file and unpack it.
  echo -n "Installing package '$ip' .... "
  ${irafdir}/util/pkgget ${REPO}/$pfile
  if ($status == 1) then
    echo    " [Error]"
    exit $status
  endif

  if (-e $pfile) then

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

    if ($src_only == 1) then
      echo    " [SOURCE ONLY]"
      echo `date +%s`"  " $ip > $ip/.src_only
    else
      echo    " [OK]"
    endif
  else
    echo    " [Error]"
  endif

  ${irafdir}/util/pkgenv -init

end

exit 0
