#!/usr/bin/env bash

#
# OVH AI CLI installation script
#
# If you're lost, start here https://docs.ovh.com/gb/en/publiccloud/ai/cli/install-client/
#

set -eu

command_exists() {
	command -v "$@" >/dev/null 2>&1
}

do_install() {
	if command_exists ovhai; then
		cat >&2 <<-'EOF'
			The ovhai CLI seems to already be installed.
			You can upgrade it using "ovhai upgrade".
		EOF
		exit 0
	fi

	if ! command_exists curl; then
		cat >&2 <<-'EOF'
			This script requires the curl binary.
			Please make sure it's installed and available in your PATH.
		EOF
		exit 1
	fi

	if ! command_exists unzip; then
		cat >&2 <<-'EOF'
			This script requires the unzip binary.
			Please make sure it's installed and available in your PATH.
		EOF
		exit 1
	fi

	# Detect OS
	OS=${OS:-$(uname | tr '[:upper:]' '[:lower:]')}
	if [ -z "$OS" ]; then
		cat >&2 <<-'EOF'
			Failed to auto-detect your operating system.
			Please run this script with OS set to "linux", "darwin" or "windows".
		EOF
	fi

	cat >&1 <<-'EOF'
		Welcome to the ovhai CLI installation script

		Running this script will download the ovhai binary and add it to your PATH.
		The ovhai CLI upgrades itself automatically when you use it.
		To uninstall, simply delete the ovhai binary.

	EOF

	# Download
	REGION=${REGION:-gra}
	REMOTE=${REMOTE:-"https://cli.$REGION.training.ai.cloud.ovh.net"}
	ARCHIVE="ovhai-$OS.zip"
	ARCHIVE_URL="$REMOTE/$ARCHIVE"
	CHECKSUM="$ARCHIVE.sha256"
	CHECKSUM_URL="$REMOTE/$CHECKSUM"
	TMP_OVHAI_BINARY_PATH=$(mktemp -d)
	trap "rm -rf \"$TMP_OVHAI_BINARY_PATH\"" EXIT
	echo "Downloading archive from $ARCHIVE_URL..."
	curl -sS "$ARCHIVE_URL" -o "$ARCHIVE"
	if command_exists sha256sum; then
		curl -sS "$CHECKSUM_URL" | sha256sum --check 1>/dev/null
	fi
	unzip -q "$ARCHIVE" -d "$TMP_OVHAI_BINARY_PATH"
	rm -f "$ARCHIVE"

	# Install
	INSTALLDIR="$HOME/bin"
	echo "Installing ovhai to $INSTALLDIR..."
	chmod +x "$TMP_OVHAI_BINARY_PATH/ovhai"
	chown "$(whoami)":"$(id -g)" "$TMP_OVHAI_BINARY_PATH/ovhai"
	mkdir -p "$INSTALLDIR"
	mv "$TMP_OVHAI_BINARY_PATH/ovhai" "$INSTALLDIR"

	if ! command_exists ovhai; then
		if [ ! -f "$HOME/.bashrc" ] || ! grep -q "$INSTALLDIR" "$HOME/.bashrc"; then
			echo "Updating PATH variable, please open a new terminal or run \"source \$HOME/.bashrc\""
			echo "export PATH=\$PATH:$INSTALLDIR" >>"$HOME/.bashrc"
		fi
		if command_exists zsh && ([ ! -f "$HOME/.zshrc" ] || ! grep -q "$INSTALLDIR" "$HOME/.zshrc"); then
			echo "export PATH=\$PATH:$INSTALLDIR" >>"$HOME/.zshrc"
		fi
	fi

	echo "Installation done!"
	echo
	echo "Feel free to check usage docs at https://docs.ovh.com/gb/en/publiccloud/ai/cli/overview-cli/"
}

# wrapped up in a function so that we have some protection against
# only getting half the file during "curl | bash"
do_install
