#!/bin/sh -x
# Upgrade to the "-latest" version of a Devious Fish project.

# -d specifies to grab from development release, not stable releases.
enabledebug=false
devel=""
[ "$1" = "-d" ] && shift && devel="/Devel" && enabledebug=true
[ "$1" = "-D" ] && shift && enabledebug=true

# Default project is pianod, but other may be specified
if [ $# -ne 1 ]
then
	[ $# -gt 1 ] && echo "$0: Too many parameters."
	echo "Usage: $0 [-d] [-D] project"
	echo "  -d : Use development release (compiled with --enable-debug if available)"
	echo "  -D : Requests --enable-debug on a stable release"
	exit 1
fi
	
project="$1"

# Clean up prior versions, save current version as -old.
rm -rf "$project-old"
[ "-s" "$project" ] && mv "$project" "$project-old"
rm "$project-latest.tar.gz"

# Find a downloader installed on this system
downloader=""
type lynx >/dev/null && downloader="links -source"
type links >/dev/null && downloader="links -source"
type curl >/dev/null && downloader=curl
type wget >/dev/null && downloader="wget -O-"

# Get it, open it, and find out where it puts the files.
if [ "$downloader" = "" ]
then
	echo "No downloader found!"
	exit 1
fi
$downloader "http://deviousfish.com/Downloads/$project$devel/$project-latest.tar.gz" > "$project-latest.tar.gz" || exit $?
tar xfvz "$project-latest.tar.gz" || exit $?
location="`tar tfz "$project-latest.tar.gz" | head -1`" || exit $?

# Try to build it
if cd "$location"
then
	configflags=""
	if [ -x ./configure ] && $enabledebug
	then
		# Determine if this package has an enable-debug flag available
		has_debug="`./configure --help | grep -cw -- --enable-debug`" 
		[ $has_debug -gt 0 ] && configflags="--enable-debug" &&
			echo "Configuring with --enable-debug"
	fi
	if [ -x ./configure ]
	then
		./configure $configflags && make && sudo make install
		status=$?
	else
		make && sudo make install
		status=$?
	fi
	# Whack any running processes so they respawn.
	if [ $status -eq 0 ]
	then
		if [ -x /usr/bin/killall -o -x /bin/killall ]
		then
			killall "$project"
		elif [ -x /usr/bin/pkill -o -x /bin/pkill ]
		then
			pkill "$project"
		fi
	fi
fi

