#!/bin/sh
# $Id: apt-get-freebsd.sh 396 2005-10-21 20:57:43Z taal $
# This is a apt-get a'like script for FreeBSD packages :)

# This should autodetect the FreeBSD release fine, however you can of course
# specify another FreeBSD mirror which is faster for you 
RELEASE=`uname -r | tr '[A-Z]' '[a-z]'`
BASEURL=`echo -n ftp://ftp.surfnet.nl/pub/os/BSD/FreeBSD/ports/i386/packages-$RELEASE`

# You have to modify this variable to point to a location where
# you have write permission as well as a lot of space (let's say
# at least 500 Mb)
CACHEDIR="/space/packages/download-cache/"

. /home/taal/scripts/functions.sh

#################
# Other Variables
MYDIR=`pwd`
ME="$0"
WGET=/usr/local/bin/wget
PKGDIR="/var/db/pkg"
INDEX="$CACHEDIR/INDEX"
if uname -r | grep -q ^4.; then
  PACKEXT="tgz"
  TAR="tar -Oxzf"
elif uname -r | grep -q ^5.; then
  PACKEXT="tbz"
  TAR="tar -Oxjf"
else
  echo "I don't recognize this version: `uname -r`"
  exit 1
fi

# Subroutines
usage() {
	echo
	echo "usage: `basename $0` \$command \$packagename"
	echo 
	echo "example 1: `basename $0` s[earch] vim"
	echo "example 2: `basename $0` i[nstall] vim"
	echo
	exit
}

choose_downloader() {
	echo -n Checking downloader...
	if [ -x $WGET ]; then
		echo WGET
		FETCH=$WGET
		ARGS="-c -nv"
	else
		echo FETCH
		FETCH=/usr/bin/fetch
		ARGS=""
	fi
}

check_index() {
	echo -n "Checking CACHEDIR..."
	if [ ! -d "$CACHEDIR" ]; then
		echo -n "not found, creating now..."
		mkdir -p "$CACHEDIR" && echo "OK" || { echo failed, exiting...; exit 2; }
	else
		echo "found."
	fi
	echo -n "Checking INDEX..."
	if [ -f "$INDEX" ]; then
		echo "found."
	else
		echo "NOT found, getting it now..."
		cd "$CACHEDIR"
		$FETCH "$BASEURL/INDEX"
	fi
}

search_index() {
	lookfor="$1"
	echo -n "Searching for '$lookfor'..."
	RESULT=`grep ^"$lookfor" "$INDEX" | cut -f 1 -d '|'`
	if [ x"$RESULT" = x"" ]; then
		echo "not found."
	else
		echo "found the following results:"
		echo "========"
		echo "$RESULT"
		echo "========"
	fi
}

install_package() {
	NUMRESULTS=`echo "$RESULT" | wc -l | xargs echo`
	if [ "$NUMRESULTS" -eq 1 -a ! x"$RESULT" = x"" ]; then
		INSTALLPACK="$RESULT"
	else
		echo "I don't know what to install"
		exit 1
	fi
	echo "Going to install $INSTALLPACK"
	PACKFILE="$INSTALLPACK.$PACKEXT"
	THISPACK="$BASEURL/All/$PACKFILE"
	$FETCH $ARGS "$THISPACK" && \
	DEPS=`$TAR "$PACKFILE" +CONTENTS | grep pkgdep | sed 's/.*pkgdep \(.*\)$/\1/g'`
	echo -n "Checking Dependencies: "
	echo $DEPS
	for d in $DEPS; do
		if [ ! -d "$PKGDIR/$d" ]; then
			echo "Installing dependency: $d..."
			cd "$MYDIR" && $ME install $d
		else
			echo OK: $d already installed
		fi
	done
	echo "Installing $INSTALLPACK now..."
	cd "$CACHEDIR" && pkg_add "$PACKFILE"  && echo "OK" || { echo "error..."; }
}

# Main() :

choose_downloader
check_index
cd "$CACHEDIR"

if [ x"$2"  = x"" ]; then
	usage
fi

case "$1" in
	s*)
		search_index "$2"
		;;
	i*)	
		search_index "$2"
		install_package "$2"
		;;
	*)
		usage
		;;
esac
exit
