#!/bin/bash
# This script tries to retrieve other scripts when they are not present on the
# client machine.  It tries to install it's first argument, and ignores the
# rest of it's arguments.
#
# reqparam value Command (script) to try and install
#

. /etc/autobench.conf || . functions

# Remove any leading arguments that are just white space
while [ -z "`echo $1`" -a $# -gt 0 ]; do
  shift
done

if [ $# -lt 1 ]; then
  echo "$0: Need the command to install"
  exit 1
fi

. $AUTODIR/var/server-repository

if [ -z "$MYIP" ]; then
    false
    check_status "unable to determine my IP"
fi

# clobber any spaces in the command...
CMD=`echo $1 | cut -f1 -d" "`

pushd $AUTODIR/scripts/user > /dev/null

# First we check the user directory --  The user directory is first in the
# path, this way they can override any command they like
which $1 2> /dev/null | grep -q "$AUTODIR/scripts/user"
if [ $? -eq 0 ]; then
  exit   # it's already in the user directory
fi
wget -q $SERVER_REPO/scripts/user/$MYIP/$CMD
chmod a+x $CMD 2> /dev/null
cd install
wget -q $SERVER_REPO/scripts/user/$MYIP/install/$CMD
chmod a+x $CMD 2> /dev/null
cd ../..

# If it's already installed somewhere in the autodir tree, bail out here.
# Check to see if it needs to be installed
which $1 2> /dev/null | grep -q $AUTODIR
if [ $? -eq 0 ]; then
  exit   # it's already installed
fi

wget -q $SERVER_REPO/scripts/$CMD
chmod a+x $CMD 2> /dev/null

cd benchmarks
wget -q $SERVER_REPO/scripts/benchmarks/$CMD
chmod a+x $CMD 2> /dev/null
cd install
wget -q $SERVER_REPO/scripts/benchmarks/install/$CMD
chmod a+x $CMD 2> /dev/null

cd ../../profilers
wget -q $SERVER_REPO/scripts/profilers/$CMD
chmod a+x $CMD 2> /dev/null
cd install
wget -q $SERVER_REPO/scripts/profilers/install/$CMD
chmod a+x $CMD 2> /dev/null

popd > /dev/null

# Check to see how we did
which $1 2> /dev/null | grep -q $AUTODIR
if [ $? -ne 0 ]; then
  # It's not in $AUTODIR
  which $1 2> /dev/null 1>&2
  if [ $? -eq 0 ]; then
    exit 3  # It's installed somehwere else
  else
    exit 2  # It's still not installed anywhere
  fi
fi

