#!/bin/sh

set -e
install_script_version=0.2.0

usage() {
	echo "Usage: $0 [options]"
	echo ""
	echo "Options:"
	echo "  -k, --key   the Level API key"
	echo "  -h, --help  print this help message"
}

# Check if sudo is installed.
if ! command -v sudo >/dev/null 2>&1; then
	printf "\033[31mLevel requires sudo to be installed\033[0m\n"
	exit 1
fi

# Root user detection
sudo_cmd=''
if test "$(id -u)" -ne "0"; then
	sudo_cmd='sudo'

	# Check if user has sudo privileges.
	if ! sudo -v; then
		printf "\033[31mInstall script requires sudo privileges\033[0m\n"
		exit 1
	fi
fi

apikey=
if [ -n "$LEVEL_API_KEY" ]; then
	apikey=$LEVEL_API_KEY
fi

while (("$#")); do
	case "$1" in
	-h | --help)
		usage
		exit 0
		;;
	-k | --key)
		if [ -n "${2:-}" ]; then
			apikey=$2
			shift 2
		else
			printf "\033[31mArgument for '${1}' is missing\033[0m\n"
			exit 1
		fi
		;;
	--dev)
		LEVEL_DEVELOPMENT="true"
		shift 1
		;;
	--latest)
		LEVEL_LATEST="true"
		shift 1
		;;
	--force)
		LEVEL_FORCE_INSTALL="true"
		shift 1
		;;
	-*)
		printf "\033[31mInvalid argument '${1}'\033[0m\n"
		exit 1
		;;
	*)
		break
		;;
	esac
done

if [ ! "$apikey" ]; then
	printf "\033[31mAPI key not available in LEVEL_API_KEY environment variable.\033[0m\n"
	exit 1
fi

if [ "$(uname)" != 'Linux' ]; then
	printf "\033[31mThis script is for Linux only.\033[0m\n"
	exit 1
fi

if [ "${LEVEL_FORCE_INSTALL:-}" != "true" ]; then
	if systemctl status Level.service >/dev/null 2>&1; then
		printf "\033[1;33mWARNING: Level service is already installed.\033[0m\n"
		exit 0
	fi
fi

# Try to get architecture from dpkg.
arch=
if ! arch=$(dpkg --print-architecture 2>/dev/null); then
	arch=""
fi

# If dpkg fails, try rpm.
if [ -z "$arch" ]; then
	arch=$(rpm --eval '%{_arch}' 2>/dev/null || true)
fi

# If both dpkg and rpm fail, use uname.
if [ -z "$arch" ]; then
	arch=$(uname -m)
fi

# Map architecture to the desired format.
case "$arch" in
amd64 | x86_64)
	arch="amd64"
	;;
armhf)
	arch="arm"
	;;
arm64 | aarch64)
	arch="arm64"
	;;
*)
	printf "\033[31mWe currently do not support the %s processor architecture.\033[0m\n" $arch
	exit 1
	;;
esac

KNOWN_DISTRIBUTION="(Debian|Ubuntu|RedHat|CentOS|openSUSE|Amazon|Arista|SUSE)"
DISTRIBUTION=$(lsb_release -d 2>/dev/null | grep -Eoi $KNOWN_DISTRIBUTION || grep -Eoi $KNOWN_DISTRIBUTION /etc/issue 2>/dev/null || grep -Eoi $KNOWN_DISTRIBUTION /etc/Eos-release 2>/dev/null || grep -m1 -Eoi $KNOWN_DISTRIBUTION /etc/os-release 2>/dev/null || uname -s)

if [ ! "$DISTRIBUTION" ]; then
	printf "\033[31mWe currently do not support this Linux distribution.\033[0m\n"
	exit 1
fi

on_error() {
	printf "\033[31m$ERROR_MESSAGE
It looks like you hit an issue when trying to install the Level Agent.
Please send an email to support@level.io or call us at 1-866-42-LEVEL
and we'll do our very best to help you solve your problem.\033[0m\n"
}
trap on_error ERR

if [ "${LEVEL_DEVELOPMENT:-}" = "true" ]; then
	printf "\033[1;33mDEVELOPMENT ONLY SCRIPT. IF YOU ARE IN A PRODUCTION ENVIRONMENT PLEASE STOP THIS SCRIPT NOW.\033[0m\n"
fi

binary_file_name="level-linux-$arch"
tmp_file="/tmp/$binary_file_name"
base_url=$([ "${LEVEL_DEVELOPMENT:-}" = "true" ] && echo "https://builds.rmm.dev" ||
	echo "https://builds.level.io")
build=$([ "${LEVEL_LATEST:-}" = "true" ] && echo "latest" || echo "stable")
url="$base_url/$build/$binary_file_name"

# Install the agent
printf "\033[34m\n* Downloading $binary_file_name\n\033[0m"
rm -f $tmp_file
curl --fail --progress-bar $url >$tmp_file
chmod +x $tmp_file

printf "\033[34m\n* Installing $binary_file_name, you might be asked for your sudo password...\n\033[0m"
printf "\033[34m\n    - Starting the agent ...\n\033[0m"

cmd="${sudo_cmd} ${tmp_file} -k ${apikey} -a install"
if [ "${LEVEL_LATEST:-}" = "true" ]; then
	cmd="${cmd} --latest"
fi

if [ "${LEVEL_DEVELOPMENT:-}" = "true" ]; then
	cmd="${cmd} --dev"
fi

eval "$cmd"
