#!/bin/sh

EULA="http://store.steampowered.com/subscriber_agreement/"

POST_MESSAGE="/var/adm/update-messages/__NAME__-__VERSION__-__RELEASE__-1"

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 /usr/bin/ar ]; 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 /usr/bin/ar ]; then
  echo "error: ar missing! Please install package ar 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

echo "EULA:"
echo -n "  Fetching   ... "
curl $CURL_OPTIONS -o /usr/share/doc/steam/subscriber-agreement $EULA || \
  rm -f /usr/share/doc/steam/subscriber-agreement
echo "done"

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_1.0.0.25.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_1.0.0.25.tar.gz
  rm steam_1.0.0.25.tar.gz
  cd steam-1.0.0.25
  # 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

test -f /usr/share/doc/steam/subscriber-agreement && w3m -dump /usr/share/doc/steam/subscriber-agreement | tee $POST_MESSAGE

popd &> /dev/null
