#!/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 -L -o /dev/null -w "%{http_code}" https://www.scala-lang.org/)"

if [ "$RETURN_CODE" != "200" ]; then
    echo "https://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 -L --fail https://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="https://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" = "centos7" -o "$DISTRO_NAME" = "rhel7" ]; then
    rpm -Uhv ${URL}/${PKG}.rpm
fi

echo "END: installing Scala"

