#!/usr/bin/env bash

#
# install-gwt
#
# Copyright (C) 2009-18 by RStudio, Inc.
#
# Unless you have received this program directly from RStudio pursuant
# to the terms of a commercial license agreement with RStudio, then
# this program is licensed to you under the terms of version 3 of the
# GNU Affero General Public License. This program is distributed WITHOUT
# ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
# AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
#
#

set -e

# install dir
INSTALL_DIR=`pwd`

# determine platform
PLATFORM=`uname`

download()
{
  if [ "$PLATFORM" == "Darwin" ]
  then
    curl -L "https://s3.amazonaws.com/rstudio-buildtools/$1" > "$1"
  else
    wget "https://s3.amazonaws.com/rstudio-buildtools/$1" -O "$1"
  fi
}

# target directory for gwt; if there's an opt folder then use that, otherwise,
# presume we're using the install dir
OPT_DEPENDENCIES="/opt/rstudio-tools/dependencies/common"
if [ -d "$OPT_DEPENDENCIES" ]; then
   GWT_DIR="$OPT_DEPENDENCIES/gwt"
else
   GWT_DIR=$INSTALL_DIR/../../src/gwt
fi

# lib dir
LIB_DIR=$GWT_DIR/lib
mkdir -p "$LIB_DIR"

# gin
GIN_VER=2.1.2
GIN=gin-$GIN_VER
GIN_ZIP=$GIN.zip
if [ -d "$LIB_DIR/gin/$GIN_VER" ]
then
   echo "$GIN_ZIP already installed"
else
   download $GIN_ZIP
   mkdir -p "$LIB_DIR/gin/$GIN_VER"
   unzip -qd "$LIB_DIR/gin/$GIN_VER" "$GIN_ZIP"
   rm $GIN_ZIP
fi

# gwt sdk
GWT_SDK_VER=2.8.1
GWT_SDK=gwt-$GWT_SDK_VER
GWT_SDK_ZIP=$GWT_SDK.zip
if [ -d "$LIB_DIR/gwt/$GWT_SDK_VER" ]
then
   echo "$GWT_SDK_ZIP already installed"
else
   download $GWT_SDK_ZIP
   mkdir -p "$LIB_DIR/gwt"
   unzip -qd "$LIB_DIR" "$GWT_SDK_ZIP"
   mv "$LIB_DIR/$GWT_SDK" "$LIB_DIR/gwt/$GWT_SDK_VER"
   rm $GWT_SDK_ZIP
fi

JUNIT_JAR=junit-4.9b3.jar
if [ -f "$LIB_DIR/$JUNIT_JAR" ]
then
    echo "$JUNIT_JAR already installed"
else
    download "$JUNIT_JAR"
    mv "$JUNIT_JAR" "$LIB_DIR/$JUNIT_JAR"
fi

# back to install dir
cd "$INSTALL_DIR"
