#!/usr/bin/env bash

#
# install-pandoc
#
# 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

source rstudio-tools

# variables that control download + installation process
PANDOC_VERSION="1.19.2.1"
PANDOC_CITEPROC_VERSION="0.10.4"
PANDOC_SUBDIR="pandoc/${PANDOC_VERSION}"
PANDOC_URL_BASE="https://s3.amazonaws.com/rstudio-buildtools/pandoc/${PANDOC_VERSION}"

# enter pandoc subdirectory
mkdir -p "${PANDOC_SUBDIR}"
pushd "${PANDOC_SUBDIR}"

# determine sub-directory based on platform
PLATFORM="$(uname)-$(getconf LONG_BIT)"
case "${PLATFORM}" in

"Darwin-64")
  SUBDIR="macos"
  FILES=(
    "pandoc-${PANDOC_VERSION}.zip"
    "pandoc-citeproc-${PANDOC_CITEPROC_VERSION}.zip"
  )
  ;;

"Linux-64")
  SUBDIR="linux-64"
  FILES=(
    "pandoc.gz"
    "pandoc-citeproc.gz"
  )
  ;;

*)
  echo "Pandoc binaries not available for platform '${PLATFORM}'."
  exit 0
  ;;

esac

# enter sub-directory
mkdir -p "${SUBDIR}"
pushd "${SUBDIR}"

# download and extract files
for FILE in "${FILES[@]}"; do
  download "${PANDOC_URL_BASE}/${SUBDIR}/${FILE}" "${FILE}"
  extract "${FILE}"
  rm -f "${FILE}"
done

# copy pandoc binaries to parent folder
cp pandoc* ..
popd

# remove transient download folder
rm -rf "${SUBDIR}"

# make pandoc executable
chmod 755 pandoc*

# and we're done!
popd

