#!/bin/bash

#
# install-libclang
#
# Copyright (C) 2009-12 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`

# use curl or wget as appropriate
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
}

# determine target platform
LIBCLANG_VERSION="3.5"
if [ "$PLATFORM" == "Darwin" ]
then
  LIBCLANG_PLATFORM=mac/x86_64
else
  if [[ -x /usr/bin/dpkg ]]
  then
    BINARY_TYPE=debian
  else
    BINARY_TYPE=rpm
  fi
  if [ "$BINARY_TYPE" == "debian" ] 
  then
    ARCH=`uname -m`
    if [ "$ARCH" == "x86_64" ]
    then
      LIBCLANG_PLATFORM=linux/x86_64
    else
      LIBCLANG_PLATFORM=NA 
    fi
  else
    LIBCLANG_PLATFORM=NA
  fi
fi

LIBCLANG_DIR="libclang/$LIBCLANG_VERSION"
if [ -d "$LIBCLANG_DIR" ]
then
   echo "libclang ${LIBCLANG_VERSION} already installed"
else
   mkdir -p "$LIBCLANG_DIR"
   if [ "$LIBCLANG_PLATFORM" != "NA" ]
   then
     LIBCLANG_SRC_PATH=libclang-${LIBCLANG_VERSION}
     LIBCLANG_ARCHIVE="${LIBCLANG_SRC_PATH}.zip"
     download $LIBCLANG_ARCHIVE
     unzip -q $LIBCLANG_ARCHIVE
     cp ${LIBCLANG_SRC_PATH}/${LIBCLANG_PLATFORM}/* ${LIBCLANG_DIR} 
     rm -rf ${LIBCLANG_SRC_PATH}
     rm $LIBCLANG_ARCHIVE
   fi
fi

LIBCLANG_HEADERS=builtin-headers
LIBCLANG_HEADERS_DIR="libclang/${LIBCLANG_HEADERS}"
if [ -d "$LIBCLANG_HEADERS_DIR" ]
then
   echo "libclang headers already installed"
else
   mkdir -p "$LIBCLANG_HEADERS_DIR"
   if [ "$LIBCLANG_PLATFORM" != "NA" ]
   then
     LIBCLANG_HEADERS_ARCHIVE="libclang-${LIBCLANG_HEADERS}.zip"
     download $LIBCLANG_HEADERS_ARCHIVE
     unzip -q $LIBCLANG_HEADERS_ARCHIVE -d libclang
     rm $LIBCLANG_HEADERS_ARCHIVE
   fi
fi


# back to install dir
cd $INSTALL_DIR
