#!/bin/bash

if [ "${DIB_DEBUG_TRACE:-0}" -gt 0 ]; then
    set -x
fi
set -eu
set -o pipefail

echo "START: installing Scala"

#Current available version
DEF_VERSION="2.11.6"

RETURN_CODE="$(curl -s -o /dev/null -w "%{http_code}" http://www.scala-lang.org/)"

if [ "$RETURN_CODE" != "200" ]; then
    echo "http://www.scala-lang.org is unreachable" && exit 1
fi

if [ -n "${SCALA_VERSION:-}" ]; then
    VERSION=${SCALA_VERSION}
elif [ "trusty" == "${DIB_RELEASE:-}" ]; then
    # scale >= 2.12 for ubuntu depends on openjdk-8, not available on trusty
    VERSION=${DEF_VERSION}
else
    VERSION="$(curl -s --fail http://www.scala-lang.org| tr -d '\n' | sed 's/^.*<div[^<]\+scala-version">[^0-9]\+\([0-9\.\?]\+\)<.\+$/\1/')"

    if [ $? != 0 -o -z "${VERSION}" ]; then
        echo "Installing default version $DEF_VERSION"
        VERSION=${DEF_VERSION}
    fi
fi

PKG=scala-${VERSION}

URL="http://downloads.lightbend.com/scala/${VERSION}"

if [ "$DISTRO_NAME" = "ubuntu" ]; then
    wget -N ${URL}/${PKG}.deb
    dpkg -i ${PKG}.deb
    rm ${PKG}.deb
elif [ "$DISTRO_NAME" = "centos" -o "$DISTRO_NAME" = "centos7" -o "$DISTRO_NAME" = "rhel" -o "$DISTRO_NAME" = "rhel7" ]; then
    rpm -Uhv ${URL}/${PKG}.rpm
fi

echo "END: installing Scala"

