#!/usr/bin/env bash

#
# install-aws-cli
#
# Copyright (C) 2025 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.
#
#

source "$(dirname "${BASH_SOURCE[0]}")/../tools/rstudio-tools.sh"
section "Installing AWS CLI"

AWS_INSTDIR="${RSTUDIO_TOOLS_ROOT}/aws-cli"
AWS_BINDIR="${AWS_INSTDIR}/bin"

# First, check for aws-cli on the PATH
AWS=$(command -v aws 2> /dev/null)
if [ -n "${AWS}" ]; then
	info "AWS CLI is already installed at ${AWS}"
	exit 0
fi

# Next, check for aws-cli in the RStudio tools directory
if command -v "${AWS_BINDIR}/aws" &> /dev/null; then
	info "AWS CLI is already installed at ${AWS_INSTDIR}"
	exit 0
fi

# The AWS CLI is not installed; install it.

case "$(uname)" in

Linux)
	sudo-if-necessary-for "${RSTUDIO_TOOLS_ROOT}" "$@"
	pushd "$(mktemp -d)"
	curl "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m).zip" -o "awscliv2.zip"
	unzip -q awscliv2.zip
	./aws/install -i "${AWS_INSTDIR}" -b "${AWS_BINDIR}"
	popd
;;

Darwin)
	brew install awscli
;;

esac

