#!/usr/bin/env bash

#
# install-sccache
#
# Copyright (C) 2023 by Posit Software, 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 "$(dirname "${BASH_SOURCE[0]}")/../tools/rstudio-tools.sh"

section "Installing sccache"

# install dir
export INSTALL_DIR="${INSTALL_DIR:-/usr/local/bin}"
if ! [ -w "$INSTALL_DIR" ]; then
    export INSTALL_DIR="$HOME/opt/bin"
fi

VERSION=0.3.1

if [ "$(arch)" = "aarch64" ] || [ "$(arch)"  = "arm64" ] ; then
    ARCH=aarch64
else
    # Assume x86_64 if not aarch64
    ARCH=x86_64
fi

echo "${ARCH}"

BASE_URL=https://github.com/mozilla/sccache/releases/download/v${VERSION}

if is-macos; then
    URL=${BASE_URL}/sccache-v${VERSION}-${ARCH}-apple-darwin.tar.gz
    if [ "${ARCH}" = "x86_64" ] ; then
        SCCACHE_PACKAGE_HASH="d8ade8d98cef392e6b256d184690e1d722f263c9f0bd83938fdd524e839c9e58"
    else
        SCCACHE_PACKAGE_HASH="303d8e905c44eb5401adc55561a4c44b36906516f3c1c0de386c4844d38151bc"
    fi
else
    # Assume Linux if not macOS
    URL=${BASE_URL}/sccache-v${VERSION}-${ARCH}-unknown-linux-musl.tar.gz
    if [ "${ARCH}" = "x86_64" ] ; then
        SCCACHE_PACKAGE_HASH="94ea33aac8dcb358753f8240cc87345963cf83cda7c6af0395dff31ffdc88df4"
    else
        SCCACHE_PACKAGE_HASH="1bf58385dc27b66324bb9ee82084e65c4d2e60baa19e3d16d2ab4da6c1ae66b2"
    fi
fi

download ${URL} sccache.tar.gz \
    && echo "${SCCACHE_PACKAGE_HASH} sccache.tar.gz" | sha256sum -c -

extract sccache.tar.gz
mkdir -p ${INSTALL_DIR}
if [ ! -f ${INSTALL_DIR}/sccache ]; then
  mv sccache-v${VERSION}-*/sccache ${INSTALL_DIR}/sccache

  chmod +x ${INSTALL_DIR}/sccache
  # this is so that boost/bjam will find and use sccache
  ln -sf ${INSTALL_DIR}/sccache ${INSTALL_DIR}/ccache

fi

rm -rf sccache*
