#!/bin/sh

POST_MESSAGE="/var/adm/update-messages/steam-1.0.0.45-lp151.1.1-1"

VERSION=1.0.0.45

SERVER="repo.steampowered.com/steam/pool/steam/s/steam"

CURL_OPTIONS="-L -s --speed-limit 3500 --speed-time 15"

if [ ! -f /usr/bin/id -o ! -f /bin/tar ]; then
 echo "Running in non-chrooted (install into directory) mode... Exit safely."
 exit 0
fi

if [ "`id -u`" != "0" ]; then
 echo "error: You must be root to use this program!"
 exit 1
fi

if [ ! -x /bin/tar ]; then
  echo "error: tar missing! Please install package tar first."
  exit 2
fi

. /etc/sysconfig/proxy

if test "$PROXY_ENABLED" != "no"; then
  if test -n "$HTTP_PROXY" ; then
    export http_proxy="$HTTP_PROXY"
  fi
fi

if [ -z $http_proxy ]; then
  echo
  echo "note: No proxy is used. Please set the environment variable \"http_proxy\""
  echo "note: to your favorite proxy if you want to use a proxy for the download."
  echo "note:"
  echo "note:   bash: export http_proxy=\"http://proxy.example.com:3128/\""
  echo "note:   tcsh: setenv http_proxy \"http://proxy.example.com:3128/\""
fi

tmpname=`basename $0`
tmpdir=`mktemp -d /tmp/$tmpname.XXXXXX`
trap "rm -rf $tmpdir" EXIT
if [ $? -ne 0 ]; then
  echo "$0: Can't create temp dir, exiting..."
  exit 4
fi

pushd $tmpdir &> /dev/null

for i in $useserver $SERVER; do
  archive=http://$i/steam_$VERSION.tar.gz
  file=`echo $archive|awk -F "/" '{print $NF}'`
  rm -f $file
  echo "$file ($archive):"
  echo -n "  Fetching   ... "
  curl $CURL_OPTIONS -o $file $archive
  if [ $? -ne 0 ]; then
    rm -f $file
    echo "failed ... deleted!"
    continue
  fi
  success=true
  echo done
  break
done

if [ "x$success" != "x" ]; then 
  # Extract
  tar -xzf steam_$VERSION.tar.gz
  rm steam_$VERSION.tar.gz
  cd steam
  # Install into system root.
  make install-bin install-docs install-icons install-bootstrap install-desktop
  # TODO: Patch it so it works with yum/zypper or at least does not invoke apt-get.
  rm /usr/bin/steamdeps
  echo "*** Steam bootstrap files installed. Run the executable to complete the installation.***" | tee $POST_MESSAGE
else
  echo "*** No Steam bootstrap files installed. ***" | tee $POST_MESSAGE
fi

popd &> /dev/null
