#!/usr/bin/env bash

#
# install-pandoc
#
# Copyright (C) 2022 by Posit Software, PBC
#
# Unless you have received this program directly from Posit Software pursuant
# to the terms of a commercial license agreement with Posit Software, 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 "$(dirname "${BASH_SOURCE[0]}")/../tools/rstudio-tools.sh"
section "Installing Pandoc"

# variables that control download + installation process
PANDOC_VERSION="3.2"
PANDOC_SUBDIR="pandoc/${PANDOC_VERSION}"
PANDOC_URL_BASE="${RSTUDIO_BUILDTOOLS}/pandoc/${PANDOC_VERSION}"

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

# move to tools root
sudo-if-necessary-for "${RSTUDIO_TOOLS_ROOT}" "$@"
cd "${RSTUDIO_TOOLS_ROOT}"

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

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

"Darwin-x86_64")
  FILES=(
    "pandoc-${PANDOC_VERSION}-x86_64-macOS.zip"
  )
  BIN_SUFFIX="-x86_64"
  ;;

"Darwin-arm64")
  FILES=(
    "pandoc-${PANDOC_VERSION}-arm64-macOS.zip"
  )
  BIN_SUFFIX="-arm64"
  ;;

"Linux-x86_64")
  FILES=(
    "pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz"
  )
  BIN_SUFFIX=""
  ;;

"Linux-aarch64")
  FILES=(
    "pandoc-${PANDOC_VERSION}-linux-arm64.tar.gz"
  )
  BIN_SUFFIX=""
  ;;

*)
  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_SUFFIX}/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

