#!/bin/sh

RPM_VERSION=__VERSION__
AIRTAME_VERSION=1.0.1-b2-11
RELEASE=b2.1
DOWNLOAD_BASE="http://downloads.airtame.com/update/beta/lin_"
POST_MESSAGE="/var/adm/update-messages/airtame-$RPM_VERSION-$RELEASE-1"
CURL_OPTIONS="-L -s --speed-limit 3500 --speed-time 15"

case "$(arch)" in
    x86_64)
        DOWNLOAD_URL="${DOWNLOAD_BASE}x64/AIRTAME-v${AIRTAME_VERSION}_x64.tar.gz"
        ;;
    i386|i486|i586)
        DOWNLOAD_URL="${DOWNLOAD_BASE}x86/AIRTAME-v${AIRTAME_VERSION}_x32.tar.gz"
        ;;
    *)
        bad_arch=true
        ;;
esac
if [ -n "$bad_arch" ]; then
    echo "Architecture not suported".
    exit 8
fi
    
if ( ! which id > /dev/null ) || ( ! which tar > /dev/null ); 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 application!"
    exit 1
fi

. "/etc/sysconfig/proxy"

if [ "$PROXY_ENABLED" != no ]; then
    if [ -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:   sh: export http_proxy=\"http://proxy.example.org:3128/\""
    echo "note:   csh: setenv http_proxy \"http://proxy.example.org:3128/\""
fi

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

abort(){
    echo "***No AIRTAME files installed: $1***" | tee $POSTMESSAGE
    exit 1
}

cd "$tmpdir"
echo "Downloading ${DOWNLOAD_URL} to ${tmpdir}"
curl $CURL_OPTIONS "$DOWNLOAD_URL" | tar -zx 2>/dev/null
if [ $? -ne 0 ]; then abort "Error downloading Airtame"; fi
mkdir -p /opt/airtame-beta
cp -a * /opt/airtame-beta/
if [ $? -ne 0 ]; then abort "Error installing to /opt/airtame-beta"; fi
echo "***AIRTAME files installed!" | tee $POSTMESSAGE
exit 0
