#!/bin/sh
# Recursive port fetching utility
# Rick van der Zwet <info@rickvanderzwet.nl>

if [ -z "$1" ]; then
  echo "Usage: $0 <packages>" 1>&2
  exit 64
else
  PACKAGELIST=$*
fi

#XXX: Make me choose the best mirror automatically
OS_RELEASE=`sysctl -n kern.osrelease | awk -F- '{print $1}'`
PKGURL=ftp://ftp.nl.freebsd.org/pub/FreeBSD/ports/i386/packages-${OS_RELEASE}-release/All
PKGDIR=$(cd `dirname $0`; pwd -P)/packages

echo "# Using PKGURL $PKGURL"
echo "# Packages get downloaded to $PKGDIR"

TMPDIR=`mktemp -d -t $(basename $0 .sh)`

FETCH='fetch -p -q -m'

err_failed() {
  echo "$*FAILED" 1>&2
  rm -R $TMPDIR
  exit 1
}

# Find longest word in string
seq_length() {
  len=`echo $* | tr ' ' '\n' | sed 's/./x/g' | sort  | tail -1 | wc -c`
  expr $len - 1
}

trap err_failed 1 2 15


# Find full release version aka long route to Latest
echo "# Finding the latest version numbers using INDEX"
$FETCH $PKGURL/../INDEX.bz2
rm -f INDEX; bunzip2 -k INDEX.bz2

len=`seq_length $PACKAGELIST`
for package in $PACKAGELIST; do
  pkg=`awk -F\| "/\/$package\|/ {print \\$1}" INDEX`
  if [ -z "$pkg" ]; then
    err_failed "# Finding version of $package "
  fi
  printf "## %-${len}s -> $pkg\n" $package
  PACKAGES="${PACKAGES} $pkg"
done

mkdir -p $PKGDIR || exit 1

PACKAGES_FETCHED=`ls $PKGDIR | sed 's/.tbz//g`
set $PACKAGES
while [ -n "$1" ]; do
  package=$1; shift
  printf "# Fetching %s ... " $package
  $FETCH -o $PKGDIR $PKGURL/$package.tbz || err_failed && echo "OK"
  PACKAGES_FETCHED="$PACKAGES_FETCHED $package"

  # Find dependencies and fetch them accordenly 
  dependencies=`tar -xjOf $PKGDIR/$package.tbz +CONTENTS |\
    awk '/^@pkgdep / {print $2}' | tr '\n' ' '`
  if [ -n "$dependencies" ]; then
    echo "## Dependencies of $package:"
  fi
  len=`seq_length $dependencies`
  for dependency in $dependencies; do
    printf "### %-${len}s : " $dependency
    echo "$PACKAGES_FETCHED" | grep -q $dependency
    if [ $? -eq 1 ]; then
      echo "Needs downloading"
      set $* $dependency
    else
      echo "PRESENT"
    fi
  done
done

rm -R $TMPDIR

echo ""
echo "# For activation and install"
echo "setenv PKG_PATH $PKGDIR"
echo "pkg_add $PACKAGES"
