#!/bin/bash

[[ $- = *i* ]] && echo "Don't source this script!" && return 10

install_arc()
{
	install_path="/usr/local/bin"
	arc_os="unsupported"
	arc_arch="unknown"

	# Fall back to /usr/bin if necessary
	if [[ ! -d $install_path ]]; then
		install_path="/usr/bin"
	fi

	# Check if sudo is needed
	((EUID)) && sudo_cmd="sudo"

	#########################
	# Which OS and arch?    #
	#########################

	arc_bin="arc"
	arc_dl_ext=".tar.gz"

	# NOTE: `uname -m` is more accurate and universal than `arch`
	# See https://en.wikipedia.org/wiki/Uname
	unamem="$(uname -m)"

	case "$unamem" in
		x86_64 | amd64) arc_arch="amd64" ;;
		i*86) arc_arch="386" ;;
		aarch64) arc_arch="arm64" ;;
		arm64) arc_arch="arm64" ;;
		*)
			echo "Aborted, unsupported or unknown architecture: $unamem"
			return 2 ;;
	esac

	unameu="$(tr '[:lower:]' '[:upper:]' <<<$(uname))"
	case "$unameu" in
		DARWIN) arc_os="darwin" ;;
		LINUX) arc_os="linux" ;;
		*WIN* | MSYS*) 
			# Should catch cygwin
			sudo_cmd=""
			arc_os="windows"
			arc_dl_ext=".zip"
			arc_bin=$arc_bin.exe
 			;;
		*)
			echo "Aborted, unsupported or unknown os: $unameu"
			return 6 ;;
	esac

	########################
	# Download and extract #
	########################

	echo "Downloading arc for ${arc_os}/${arc_arch}..."
	arc_file="arc_latest_${arc_os}_${arc_arch}${arc_dl_ext}"
	arc_url="https://registry.eui.io/arc/latest/arc_latest_${arc_os}_${arc_arch}${arc_dl_ext}"

	dl="$PREFIX/tmp/$arc_file"
	rm -rf -- "$dl"

	if type -p curl >/dev/null 2>&1; then
		curl -fsSL "$arc_url" -o "$dl"
	elif type -p wget >/dev/null 2>&1; then
		wget --quiet "$arc_url" -O "$dl"
	else
		echo "Aborted, could not find curl or wget"
		return 7
	fi

	# Extract download

	echo "Extracting..."
	case "$arc_file" in
		*.zip)    unzip -o "$dl" "$arc_bin" -d "$PREFIX/tmp/" ;;
		*.tar.gz) tar -xzf "$dl" -C "$PREFIX/tmp/" "$arc_bin" ;;
	esac
	chmod +x "$PREFIX/tmp/$arc_bin"

	# Back up existing arc, if any found in path
	if arc_path="$(type -p "$arc_bin")"; then
		arc_backup="${arc_path}_old"
		echo "Backing up $arc_path to $arc_backup"
		echo "(Password may be required.)"
		$sudo_cmd mv "$arc_path" "$arc_backup"
	fi

	echo "Putting arc in $install_path (may require password)"
	$sudo_cmd mv "$PREFIX/tmp/$arc_bin" "$install_path/$arc_bin"
	$sudo_cmd rm -- "$dl"

	# check installation
	# $arc_bin tutorial

	echo ""
	echo "Install complete"
	echo "Check the install & PATH by invoking 'arc info'"
	return 0
}

install_arc "$@"
