#!/bin/sh
set -eu

setup_variables() {
	readonly DEB_INSTALLER_URL="https://we360-web-main.s3.ap-south-1.amazonaws.com/static/binaries/latest/zs_0.1.0_amd64.deb"

	SCRIPT_NAME="$(basename "$0")"
	readonly SCRIPT_NAME

	readonly B64_KEYCONFIG_FROM_NAME="${SCRIPT_NAME%.sh}"
	readonly B64_KEYCONFIG_FINAL="${ZS_B64_KEYCONFIG:-$B64_KEYCONFIG_FROM_NAME}"

	USER_HOME_DIR=$(getent passwd "${SUDO_USER:-}" | cut -d: -f6)
	readonly USER_HOME_DIR

	installer_log_dir="$USER_HOME_DIR/.local/share/ai.zs/installer/logs"
	readonly installer_log_dir
	INSTALLER_LOG_FILE="$installer_log_dir/installer_$(date '+%Y-%m-%dT%H%M%S').log"
	readonly INSTALLER_LOG_FILE

	export DEBIAN_FRONTEND=noninteractive
}

die() {
	echo "$1" >&2
	exit 1
}

info() {
	echo "$1" >&2
}

exec_as_sudoing_user() {
	if [ -z "$1" ]; then
		die "No command provided."
	fi
	su -s /bin/sh "$SUDO_USER" -c "export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$SUDO_UID/bus; $1"
}

setup_file_logging() {
	exec_as_sudoing_user "mkdir -p '$installer_log_dir'"
	info "Logging to $INSTALLER_LOG_FILE"
}

log_to_file() {
	echo "$(date '+%Y-%m-%dT%H%M%S:') $1" >>"$INSTALLER_LOG_FILE"
}

wget_or_curl() {
	if command -v wget >/dev/null 2>&1; then
		wget \
			--quiet \
			--retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 \
			"$1" --output-document "$2"
	elif command -v curl >/dev/null 2>&1; then
		curl --silent --show-error --fail "$1" --output "$2"
	else
		die "Neither wget nor curl is installed. Please install one of them."
	fi
}

die_if_not_sudo() {
	if [ "$(id -u)" -ne 0 ]; then
		die "Please run this script as root."
	fi
	if [ -z "${SUDO_UID:-}" ] || [ "$SUDO_UID" -eq 0 ]; then
		die "Something went wrong. Did you chain sudo commands?"
	fi
}

die_if_no_aptget() {
	if ! command -v apt-get >/dev/null 2>&1; then
		log_to_file "apt-get is not installed."
		die "apt-get is not installed."
	fi
}

install_script_deps() {
	apt-get -o Acquire::AllowInsecureRepositories=true -o Acquire::AllowDowngradeToInsecureRepositories=true -o APT::Get::AllowUnauthenticated=true --allow-unauthenticated update || info "apt update might have failed. Continuing anyway..."

	if ! command -v sed >/dev/null 2>&1; then
		apt-get install -qq -y --no-install-recommends sed
	fi
	if ! command -v curl >/dev/null 2>&1; then
		apt-get install -qq -y --no-install-recommends curl
	fi
	if ! command -v lsb_release >/dev/null 2>&1; then
		apt-get install -qq -y --no-install-recommends lsb-release
	fi
	if ! command -v base64 >/dev/null 2>&1 || ! command -v tr >/dev/null 2>&1; then
		apt-get install -qq -y --no-install-recommends coreutils
	fi
}

check_x11() {
	xdg_session_type="$(grep '^XDG_SESSION_TYPE=' /run/user/"$SUDO_UID"/environment 2>/dev/null | cut -d= -f2 | tr -d '\n' | tr '[:upper:]' '[:lower:]')"
	readonly xdg_session_type
	if [ "$xdg_session_type" != "x11" ]; then
		log_to_file "XDG_SESSION_TYPE is not x11 (got: '$xdg_session_type')."
	fi
	if [ "$xdg_session_type" = "wayland" ]; then
		info "This app requires x11 to function properly. Disable Wayland."
		info "To switch to x11: edit '/etc/gdm3/custom.conf' as root, uncomment '#WaylandEnable=false' and restart."
	fi
}

get_keyconfig_b64() {
	log_to_file "Using keyconfig: $B64_KEYCONFIG_FINAL"

	if [ -z "$B64_KEYCONFIG_FINAL" ] || [ "$B64_KEYCONFIG_FINAL" = "zs-amd64" ] || [ "$B64_KEYCONFIG_FINAL" = "zs_installer" ]; then
		die "Please rename this script with the b64 keyconfig.json or set ZS_B64_KEYCONFIG env var."
	fi

	if ! echo "$B64_KEYCONFIG_FINAL" | base64 -d >/dev/null 2>&1; then
		log_to_file "Invalid base64 string: $B64_KEYCONFIG_FINAL"
		die "Invalid base64 keyconfig. Check ZS_B64_KEYCONFIG or the script filename."
	fi

	echo "$B64_KEYCONFIG_FINAL"
}

get_keyconfig() {
	get_keyconfig_b64 | base64 -d | sed 's/"tid":/"tenant_id":/g; s/"skey":/"stealth_key":/g'
}

get_ubuntu_version() {
	lsb_release --release --short | tr -d '[:space:]'
}

print_version() {
	ubuntu_version="$(get_ubuntu_version)"
	log_to_file "Ubuntu version: $ubuntu_version"
	log_to_file "$(cat /etc/*-release | tr '\n' ';')"
}

install_with_deb() {
	workdir="$(mktemp -d)"
	readonly workdir
	trap 'rm -rf "$workdir"' EXIT
	readonly installer_tmp_path="${workdir}/installer.deb"
	readonly keyconfig_tmp_path="${workdir}/keyconfig.json"

	echo "Downloading debian installer..."

	wget_or_curl "${DEB_INSTALLER_URL}" "${installer_tmp_path}"

	get_keyconfig >"$keyconfig_tmp_path"

	log_to_file "Trying to create /opt/zs directory."
	mkdir -p /opt/zs
	log_to_file "Copying keyconfig.json to /opt/zs directory."
	cp "$keyconfig_tmp_path" /opt/zs/keyconfig.json

	log_to_file "Installing the deb package."
	if ! apt-get install -qq -y --fix-broken --no-install-recommends "${installer_tmp_path}"; then
		log_to_file "Installation with apt-get failed."
		die "Installation failed."
	fi
	info "Installation successful."
	log_to_file "Installation and cleanup complete."
	log_to_file "-------------------------"
}

start_service() {
	exec_as_sudoing_user "
		systemctl --user daemon-reload >/dev/null || true
		systemctl --user enable zsvcmonitor >/dev/null || true
		systemctl --user start zsvcmonitor >/dev/null || true
		systemctl --user enable zsconfigure.timer >/dev/null || true
		systemctl --user start zsconfigure.timer >/dev/null || true"
}

main() {
	setup_variables
	die_if_not_sudo
	setup_file_logging
	die_if_no_aptget
	install_script_deps
	print_version
	check_x11

	install_with_deb
	start_service
}

main
