#!/bin/sh
#
# getpkg - retrieves a single package from package server
#
# Author: Matthew D. Franz <mdfranz@io.com>
#
# $1 - name of package
# $2 - URL of server
#
############################################################################

[ -d /var/pkg/contents ] || mkdir -p /var/pkg/contents

if [ -f /etc/tux/config/proxy ]
then
	SNARF_PROXY=`cat /etc/tux/config/proxy`
	export SNARF_PROXY
fi

mkdir /etc/init.d/running 2> /dev/null

if [ "$1" = "list" ]
then
	pkglist
	exit
fi

if [ "$1" = "all" ]
	then
		echo "Downloading all packages..."

		if [ ! -f /etc/tux/config/eth0 ]
		then
			echo "Network was not configured"
			if dmesg | grep eth0 > /dev/null
			then	
				echo -n "Attempting DHCP on eth0: "
				if dhcpcd > /dev/null 2> /dev/null
				then
					echo "Successful"
				else
					echo "Failed"
					exit
				fi
			else
				echo "No ethernet interfaces were found"
				exit
			fi
		fi

		if [ -f /etc/tux/config/pkglist ]
		then
			pkglist=`cat /etc/tux/config/pkglist`
			for i in $pkglist
			do
				getpkg $i
			done
		else
			echo "No package list found, retrieving a minimal set"
			getpkg baselib
			getpkg term
			getpkg vi
			getpkg tcpdump
		fi

		exit 
fi

if [ "$1" = "" ]
then
	echo; echo "You did not specify a package or server!"; echo	
	echo "getpkg all will load all the packages from /etc/tux/config/pkglist"
	getpkg all 
else
	if [ "$2" = "" ]
		then
		if [ "$URL" = "" ]
		then
			if [ -f /etc/tux/config/server ]
			then
				blah=1
			else
				echo -n "Enter URL for package retrieval: "
				read URL
				if [ "$URL" != "" ] 
				then
					echo "Using $URL as your package server from now on..."
					echo "$URL" > /etc/tux/config/server
				fi
			fi
		fi
	else
			URL=$2	
	fi

	if echo $1 | grep tgz > /dev/null
	then
		FILE=$1
	else
		FILE=$1.tgz
	fi

	cd /

	PREFIX=`basename $FILE ".tgz"`

	#echo $PREFIX	

	MODPKGNAME=`echo ${1} | cut -d'/' -f2`


	if echo $MODPKGNAME | grep tgz > /dev/null
	then
		MODPKGNAME=`basename $MODPKGNAME ".tgz"`
	fi

	# Loop through servers listed in  

	for URL in `cat /etc/tux/config/server`
	do
		if snarf $URL - > /dev/null 2> /dev/null
		then
			echo "Retrieving ${URL}${FILE}"
			output=`snarf ${URL}/${FILE} - | gunzip -c | tar xvf -`
		fi 

		echo $output > /var/pkg/contents/$PREFIX

		if [ -f /etc/init.d/${PREFIX} ]
		then		
			chmod a+x /etc/init.d/${PREFIX} 2> /dev/null
			echo; echo "Initializing ${PREFIX}"
			/etc/init.d/${PREFIX} 2>  /dev/null
		fi


		if [ "$MODPKGNAME" ]
		then		
			chmod a+x /etc/init.m/${MODPKGNAME} 2> /dev/null
			if [ -x /etc/init.m/$MODPKGNAME ]
			then
				/etc/init.m/$MODPKGNAME
				echo "Initializing $1 modules"
			fi
		fi


		break
	done

	[ $? -eq 0 ] || exit 1

fi

