#!/bin/sh

NAME=skype-legacy
VERSION=4.3.0.37
POST_MESSAGE="/var/adm/update-messages/skype-legacy-4.3.0.37-2.6-1"

SERVER="https://download.skype.com/linux"
FILE="skype-$VERSION.tar.bz2"

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

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 favourite 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

cd "$tmpdir"

for server in $useserver $SERVER; do
    archive="$server/$FILE"
    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 [ "$success" != "" ]; then
    # Extract.
    tar -xjf "$FILE"
    rm -f "$FILE"
    cd "skype-$VERSION"
    # Install into system root.
    sed -i \
      -e "s/^Exec=.*$/Exec=$NAME %U/"       \
      -e "s/^Icon=.*$/Icon=$NAME/"          \
      -e "s/^Name=.*$/Name=Skype (Legacy)/" \
      "skype.desktop"
    install -Dpm 0755 "skype" "/usr/lib/$NAME/skype"
    install -Dpm 0644 "skype.desktop" "/usr/share/applications/$NAME.desktop"
    for dir in "avatars" "lang" "sounds"; do
        mkdir -p "/usr/share/$NAME/$dir/"
        install -pm 0644 "$dir/"* "/usr/share/$NAME/$dir/"
    done
    for size in 16 24 32 48 64 96 128 256; do
        mkdir -p "/usr/share/icons/hicolor/${size}x${size}/apps/"
        cp -f "icons/SkypeBlue_${size}x${size}.png" \
          "/usr/share/icons/hicolor/${size}x${size}/apps/$NAME.png"
    done
    # UNIXifying and installing the licence file.
    sed -i 's/\r$//' "LICENSE"
    install -Dpm 0644 "LICENSE" "/usr/share/doc/packages/$NAME/COPYING"

    gtk-update-icon-cache --quiet --force "/usr/share/icons/hicolor/"

    echo "*** Legacy Skype files installed. ***" | tee $POST_MESSAGE
else
    echo "*** No Legacy Skype files installed. ***" | tee $POST_MESSAGE
fi

if [ -f "/usr/share/doc/packages/$NAME/COPYING" ]; then
    cat "/usr/share/doc/packages/$NAME/COPYING" | tee $POST_MESSAGE
fi
