#!/usr/bin/env bash

#
# install-pandoc
#
# Copyright (C) 2009-19 by RStudio, PBC
#
# 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="2.7.3"
PANDOC_SUBDIR="pandoc/${PANDOC_VERSION}"
PANDOC_URL_BASE="https://s3.amazonaws.com/rstudio-buildtools/pandoc/${PANDOC_VERSION}"

# see if we already have binaries
if [ -d "${PANDOC_SUBDIR}" ]; then
    echo "Pandoc ${PANDOC_VERSION} already installed"
    exit 0
fi

# 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}-macOS.zip"
  )
  ;;

"Linux-64")
  SUBDIR="linux"
  FILES=(
    "pandoc-${PANDOC_VERSION}-linux.tar.gz"
  )
  ;;

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

esac

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

# enter binaries dir
pushd "pandoc-${PANDOC_VERSION}/bin"

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

# leave binaries dir
popd

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

# make pandoc executable
chmod 755 pandoc*

# and we're done!
popd

