#!/bin/sh
set -e

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

install() {
  arch="$(uname -m)"
  os="$(uname)"
	case "$arch" in
		*64)
			;;
		*)
			cat >&2 <<-"EOF"
			Error: you are not using a 64-bit platform
			Buddy currently supports only 64-bit platforms
			EOF
			exit 1
			;;
	esac

	user="$(id -un 2>/dev/null || true)"
	shc="sh -c"
	if [ "$user" != "root" ]; then
		if cmde sudo; then
			shc="sudo -E sh -c"
		else
			cat >&2 <<-"EOF"
			Error: this installer must be able to run commands as root
			Unable to find "sudo" to perform the operation
			EOF
			exit 1
		fi
	fi

	curl=""
	if cmde curl; then
		curl="curl -sSL"
	elif cmde wget; then
		curl="wget -qO-"
	elif cmde busybox && busybox --list-modules | grep -q wget; then
		curl="busybox wget -qO-"
	else
	    cat >&2 <<-"EOF"
			Error: this installer must be able to download files
			Unable to find "curl" or "wget" to perform the operation
			EOF
			exit 1
	fi

	if [ "$os" = "Darwin" ]; then
	  if [ "$arch" = "arm64" ] || [ "$arch" = "aarch64" ]; then
	    sufix="mac_arm"
	  else
	    sufix="mac"
	  fi
	else
    if [ "$arch" = "arm64" ] || [ "$arch" = "aarch64" ]; then
      sufix="linux_arm"
    else
      sufix="linux"
    fi
	fi
  url="https://es.buddy.works/cli/download/$sufix/buddy"
  echo "Downloading Buddy CLI..."
  $shc "$curl $url > /usr/local/bin/buddy"
  $shc "chmod +x /usr/local/bin/buddy"
  $shc "buddy --silent > /dev/null 2>&1 || true"
  echo "Download complete. Type buddy to launch the CLI"
}

install "$@"