#!/usr/bin/env bash
#
#                  Relica Installer Script
#
#   Homepage: https://relicabackup.com
#   Requires: bash, mv, rm, tr, type, curl/wget, base64, sudo (if not root)
#             tar (or unzip on macOS), gpg (optional verification)
#
# This script safely installs Relica:
#
#	$ curl https://relica.run | bash
#	 or
#	$ wget -qO- https://relica.run | bash
#
# Note that you may be prompted for sudoer password.
# On Linux, systemd is required to run Relica properly.
#
# This should work on Mac and Linux systems. Windows
# is not supported by this script, sorry; but you can
# can still install Relica on Windows with the
# regular installer.
#
# For 32-bit ARM architectures: ARMv7 is required.
#

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

install_relica()
{
	trap 'echo -e "Aborted, error $? in command: $BASH_COMMAND"; trap ERR; exit 1' ERR
	relica_os="unsupported"
	relica_arch="unknown"
	relica_arm=""

	#########################
	# Which OS and version? #
	#########################

	relica_bin="relica"
	relica_dl_ext=".tar.gz"

	# NOTE: `uname -m` is more accurate and universal than `arch`
	# See https://en.wikipedia.org/wiki/Uname
	unamem="$(uname -m)"
	if [[ $unamem == *aarch64* ]]; then
		relica_arch="arm64"
	elif [[ $unamem == *64* ]]; then
		relica_arch="amd64"
	elif [[ $unamem == *86* ]]; then
		relica_arch="386"
	elif [[ $unamem == *armv5* ]]; then
		relica_arch="arm"
		relica_arm="5"
	elif [[ $unamem == *armv6l* ]]; then
		relica_arch="arm"
		relica_arm="6"
	elif [[ $unamem == *armv7l* ]]; then
		relica_arch="arm"
		relica_arm="7"
	else
		echo "Aborted, unsupported or unknown architecture: $unamem"
		return 2
	fi

	unameu="$(tr '[:lower:]' '[:upper:]' <<<$(uname))"
	if [[ $unameu == *DARWIN* ]]; then
		relica_os="darwin"
		relica_dl_ext=".zip"
		vers=$(sw_vers)
		version=${vers##*ProductVersion:}
		IFS='.' read OSX_MAJOR OSX_MINOR _ <<<"$version"

		# Major
		if ((OSX_MAJOR < 10)); then
			echo "Aborted, unsupported OS X version (9-)"
			return 3
		fi
		if ((OSX_MAJOR > 10)); then
			echo "Aborted, unsupported OS X version (11+)"
			return 4
		fi

		# Minor
		if ((OSX_MINOR < 5)); then
			echo "Aborted, unsupported OS X version (10.5-)"
			return 5
		fi
	elif [[ $unameu == *LINUX* ]]; then
		relica_os="linux"
	# elif [[ $unameu == *FREEBSD* ]]; then
	# 	relica_os="freebsd"
	# elif [[ $unameu == *OPENBSD* ]]; then
	# 	relica_os="openbsd"
	else
		echo "Aborted, unsupported or unknown os: $uname"
		return 6
	fi

	# get latest version (it's JSON string output, so strip quotes)
	api_endpoint="https://relicabackup.com/api/latest-version?os=${relica_os}"
	if type -p curl >/dev/null 2>&1; then
		relica_ver=$(curl -s "${api_endpoint}")
	elif type -p wget >/dev/null 2>&1; then
		relica_ver=$(wget -qO- "${api_endpoint}")
	fi
	

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

	echo "Downloading Relica ${relica_ver} for ${relica_os}/${relica_arch}..."
	relica_file="relica_v${relica_ver}_${relica_os}_${relica_arch}_upgrade${relica_dl_ext}"
	relica_url="https://relica-releases.s3.wasabisys.com/dist/v${relica_ver}/${relica_file}"
	relica_asc="${relica_url}.asc"

	type -p gpg >/dev/null 2>&1 && gpg=1 || gpg=0

	# Use $PREFIX for compatibility with Termux on Android
	dl="$PREFIX/tmp/$relica_file"
	rm -rf -- "$dl"

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

	# Verify download
	if ((gpg)); then
		keyservers=(
			ha.pool.sks-keyservers.net
			hkps.pool.sks-keyservers.net
			pool.sks-keyservers.net
			keyserver.ubuntu.com)
		keyserver_ok=0 n_keyserver=${#keyservers[@]}
		relica_pgp="75B35F8189EC5932D717C73CD8276B3451CAD12C"
		while ((!keyserver_ok && n_keyserver))
		do
			((n_keyserver--))
			gpg --keyserver ${keyservers[$n_keyserver]} --recv-keys $relica_pgp >/dev/null 2>&1 &&
				keyserver_ok=1
		done
		if ((!keyserver_ok))
		then
			echo "No valid response from keyservers"
		elif gpg -q --batch --verify "$dl.asc" "$dl" >/dev/null; then
			rm -- "$dl.asc"
			echo "Download verification OK"
		else
			rm -- "$dl.asc"
			echo "Aborted, download verification failed"
			return 8
		fi
	else
		echo "Notice: download verification not possible because gpg is not installed"
	fi

	# Install and add to PATH
	echo "Extracting (may require sudoer password)..."
	if [ "$relica_os" == "darwin" ]; then
		appdir="/Applications/Relica.app"
		mkdir -p "$appdir"
		unzip "$dl" -d "$appdir"
		export PATH=$PATH:$appdir/Contents/MacOS
	elif [ "$relica_os" == "linux" ]; then
		sudo tar -xzf "$dl" -C "/opt"
		sudo chown -R $(id -u):$(id -g) /opt/relica
		export PATH=$PATH:/opt/relica/bin
	else
		echo "Aborted; unsupported OS and thus unknown install procedure"
	fi

	# Clean up
	rm -- "$dl"

	# libpam-systemd is required for `systemctl --user` (Linux)
	# (otherwise obscure "Failed to get D-Bus connection: Connection refused" error is emitted)
	if [ "$relica_os" == "linux" ] && type -p apt >/dev/null 2>&1; then
		echo "Ensuring libpam-systemd is installed (may require sudoer password)..."
		sudo apt update
		sudo apt install -y libpam-systemd
	fi

	# Run the daemon as a system service
	relica install

	# Show successful install information
	echo "Successfully installed"
	which relica
	relica version

	trap ERR
	return 0
}

install_relica