#!/usr/bin/env bash

# Installation script for the SAP BTP command line interface client
# Source: https://cli.btp.cloud.sap/btpcli-install.sh
# Downloads the client archive, validates the checksum and expands the executable into a local folder

set -e -u -o pipefail -o noclobber

# Uncomment the line below to activate debug output
# set -x

echo ""
echo "SAP BTP command line interface (btp CLI) installation"
echo ""

# default values for version and output directory
defaultVersion=latest
defaultOutDir=/usr/local/bin
help=false

# initialize actual values with defaults
version=$defaultVersion
outDir=$defaultOutDir

OPTIONS=qo:v:h
while getopts "$OPTIONS" opt; do
	case "$opt" in
	h)
		help=true
		;;
	v)
		version="$OPTARG"
		;;
	o)
		outDir="$OPTARG"
		;;
	esac
done
shift $((OPTIND - 1))
# shellcheck disable=SC2199
if [[ -n "$@" ]]; then
	help=true
fi

if [[ $help == true ]]; then
	echo "The following arguments are available:"
	echo " -o [directory] Specifies the directory to place btp CLI in (e.g.: ~/Downloads). Default: $defaultOutDir"
	echo " -v [version]   Specifies the btp CLI version to be installed (e.g.: 2.61.1). Default: $defaultVersion"
	echo " -h             Show this help"
	exit 0
else
	echo "Use option -h to see a list of available arguments"
	echo ""
fi

outDir=$(realpath "$outDir")

# make sure the output path is not blocked by a file
if [[ -f $outDir ]]; then
	echo "$outDir is a file, but you can only install into a folder"
	exit 1
fi
# make sure the output path exists
if [[ ! -d $outDir ]]; then
	echo "Output directory $outDir does not exist"
	exit 1
fi
# determine arch and os
arch=unknown
case $(uname -m) in
x86_64) arch="amd64" ;;
arm64) arch="arm64" ;;
aarch64) arch="arm64" ;;
arm) echo "Could not determine exact ARM version from 'uname -m'. Defaulting to 'arm64'" && arch="arm64" ;;
*) echo "OS architecture could not be detected" && exit 1 ;;
esac

os=unknown
case $(uname -s) in
Linux) os="linux" ;;
Darwin) os="darwin" ;;
*) echo "OS could not be identified" && exit 1 ;;
esac

echo "This script will download the btp CLI client (version: $version) and place it in $outDir"
echo "If you already have a version of btp CLI installed, it will be overwritten"
echo ""

# we create a temporary folder for download
tmpInstallDir=/tmp/btpcliinstaller
if [[ -d $tmpInstallDir ]]; then
	if [[ -w $tmpInstallDir ]]; then
		rm -rf $tmpInstallDir
	else
		echo "The temporary working directory for the btp CLI installation could not be cleaned due to insufficient permissions. Trying again with sudo to allow cleaning $tmpInstallDir"
		sudo rm -rf $tmpInstallDir
	fi
fi
mkdir -p $tmpInstallDir

# check if version can be downloaded
archiveDownloadUrl=https://tools.hana.ondemand.com/additional/btp-cli-${os}-${arch}-${version}.tar.gz
localZipPath=$tmpInstallDir/btpcli.tar.gz
rc=$(curl -s --output /dev/null --write-out '%{http_code}' --head $archiveDownloadUrl)
if [[ $rc -ge "400" ]]; then
	echo "Could not download archive (version $version) from $archiveDownloadUrl, perhaps the version is wrong"
	exit 1
fi

echo "Downloading archive from $archiveDownloadUrl..."
curl -s --header "Cookie: eula_3_2_agreed=tools.hana.ondemand.com/developer-license-3_2.txt" $archiveDownloadUrl -o $localZipPath

sha1DownloadUrl=$archiveDownloadUrl.sha1
localSha1Path=$localZipPath.sha1

BTPCLI_SKIP_SHA1CHECK=${BTPCLI_SKIP_SHA1CHECK:-false}
if $BTPCLI_SKIP_SHA1CHECK; then
	echo "Skipping SHA1 checksum check"
elif command -v shasum &> /dev/null; then
	echo "SHA1 Checksum check..."
	curl -s $sha1DownloadUrl > $localSha1Path && echo " *$localZipPath" >> $localSha1Path
	if ! shasum -a 1 -c $localSha1Path; then
		echo "error: SHA1 checksum does not match"
		exit 1
	fi
elif command -v sha1sum &> /dev/null; then
	echo "SHA1 Checksum check..."
	curl -s $sha1DownloadUrl > $localSha1Path && echo " *$localZipPath" >> $localSha1Path
	if ! sha1sum -c $localSha1Path; then
		echo "error: SHA1 checksum does not match"
		exit 1
	fi
else
	echo "error: No SHA1 tool found. Use 'export BTPCLI_SKIP_SHA1CHECK=true' to skip the SHA1 check"
	exit 1
fi

echo "Extracting archive"
tar -xzf $localZipPath --directory $tmpInstallDir --no-same-owner
echo "Moving btp to $outDir"
if [[ -w $outDir ]]; then
	mv $tmpInstallDir/${os}-$arch/btp "$outDir"
else
	echo "The output directory specified can not be written due to insufficient permissions. Trying again with sudo to allow placing btp CLI in $outDir"
	sudo mv $tmpInstallDir/${os}-$arch/btp "$outDir"
fi
trap 'rm -rf $tmpInstallDir' EXIT

if [[ "$outDir" != "$defaultOutDir" ]]; then
	echo "Since you did not use the default installation location, you might want to add $outDir to your PATH"
fi
echo ""
echo "Note: By installing the SAP BTP command line interface (btp CLI), you AGREE to the license terms at: https://tools.hana.ondemand.com/developer-license-3_2.txt"
