#!/bin/sh
#
# Copyright (c) 2004-2012 University of Utah and the Flux Group.
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#

version=2.0
srcurl="http://www.postel.org/tg"
tarball="tg${version}.tar.gz"

if [ -x /usr/bin/fetch ]; then
    fetch=/usr/bin/fetch
elif [ -x /usr/bin/wget ]; then
    fetch=/usr/bin/wget
else
    echo "ERROR: tg-install: need either 'fetch' or 'wget' installed"
    exit 1
fi

if [ -n "$1" ]; then srcdir=$1; else srcdir=$PWD ; fi
if [ -n "$2" ]; then tarball=$2; fi
if [ -n "$3" ]; then host=$3; else host=www.emulab.net ; fi
dir=`pwd`

if [ ! -d $dir/tg${version}/src ]; then
    if [ ! -f "$tarball" ]; then
      cd $dir
      echo "Downloading tg source from $host to $dir ..."
      $fetch http://$host/$tarball
      if [ $? -ne 0 ]; then
           echo "Failed..."
           echo "Downloading tg source from \"$srcurl\" to $dir ..."
           $fetch "$srcurl/$tarball" || {
	       echo "ERROR: tg-install: $fetch failed"
	       exit 1
	   }
      fi
    fi
    echo "Unpacking/patching tg${version} source ..."
    tar xzof $tarball || {
        echo "ERROR: tg-install: tar failed"
	exit 1
    }
    patch -p0 < $srcdir/tg.patch || {
        echo "ERROR: tg-install: patch failed"
	exit 1
    }
    rm -f tg${version}/*/*/*.orig
fi
exit 0
