#!/usr/bin/env bash

#
# install-openssl
#
# Copyright (C) 2026 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 OpenSSL"

OPENSSL_VERSION="${RSTUDIO_OPENSSL_VERSION}"

# install-dependencies-osx runs this under 'arch -<arch>' for each
# architecture it installs, with RSTUDIO_TOOLS_ROOT set to match
ARCH="$(uname -m)"
OPENSSL_DIR="${RSTUDIO_TOOLS_ROOT}/openssl-${OPENSSL_VERSION}"
OPENSSL_ARCHIVE="openssl-${OPENSSL_VERSION}-macos-${ARCH}.tar.gz"
OPENSSL_URL="${RSTUDIO_BUILDTOOLS}/${OPENSSL_ARCHIVE}"

# SHA-256 of the archives build-openssl built and upload-openssl.sh published;
# pinned so a replaced archive in the bucket can't reach the signed app
case "${ARCH}" in
arm64)  OPENSSL_SHA256="75e699a94db71aa1b2a2f18f2ccac0c7c71153ba6f10c9f43f99bf8ffcc53b6c" ;;
x86_64) OPENSSL_SHA256="134dba69ada51e60e9b938c8c5a0385fb4fd06f32e181371ce5dd2907aefdcd3" ;;
*)      error "unknown architecture '${ARCH}'; expected x86_64 or arm64" ;;
esac

if [ -d "${OPENSSL_DIR}" ]; then
   info "OpenSSL ${OPENSSL_VERSION} already installed at '${OPENSSL_DIR}'"
   exit 0
fi

sudo-if-necessary-for "${RSTUDIO_TOOLS_ROOT}" "$@"

# unpack and check the archive beside the install, and move it into place only
# once it's complete, so an interrupted install is never taken for a finished one
STAGING_DIR="$(mktemp -d "${RSTUDIO_TOOLS_ROOT}/.openssl-XXXXXX")"
trap 'rm -rf "${STAGING_DIR}"' EXIT
STAGED_DIR="${STAGING_DIR}/openssl-${OPENSSL_VERSION}"

download "${OPENSSL_URL}" "${STAGING_DIR}/${OPENSSL_ARCHIVE}"
if ! echo "${OPENSSL_SHA256}  ${STAGING_DIR}/${OPENSSL_ARCHIVE}" |
      shasum -a 256 -c - > /dev/null; then
   error "'${OPENSSL_URL}' doesn't match OPENSSL_SHA256; if the version changed, update it"
fi
tar -xf "${STAGING_DIR}/${OPENSSL_ARCHIVE}" -C "${STAGING_DIR}"

if ! [ -f "${STAGED_DIR}/include/openssl/ssl.h" ]; then
   error "'${OPENSSL_URL}' has no openssl-${OPENSSL_VERSION}/include/openssl/ssl.h"
fi

# a mislabeled archive would otherwise surface only as link errors much later
for LIB in libcrypto.a libssl.a; do
   if ! [ -f "${STAGED_DIR}/lib/${LIB}" ]; then
      error "'${OPENSSL_URL}' has no openssl-${OPENSSL_VERSION}/lib/${LIB}"
   fi
   LIB_ARCHS="$(lipo -archs "${STAGED_DIR}/lib/${LIB}")"
   if [ "${LIB_ARCHS}" != "${ARCH}" ]; then
      error "'${OPENSSL_URL}' has ${LIB} for ${LIB_ARCHS}; expected ${ARCH}"
   fi
done

mv "${STAGED_DIR}" "${OPENSSL_DIR}"
