#!/bin/bash

[ -n "${PREFIX}" ] && { echo >&2 "ERROR: Prefix installations are not supported, use make instead."; exit 1; }

if [ ${EUID} -ne 0 ]; then
	echo >&2 "ERROR: You most probably need superuser privileges to use this script, please run me via sudo!"
	exit 3
fi

# shellcheck disable=SC2034
GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || true)

__version() {
	git describe --tags --dirty 2>/dev/null || sed -re's/v?(.*)/v\1/' "$(dirname "${BASH_SOURCE[0]}")/../VERSION" || {
		echo >&2 "ERROR: If you install from a git repository, you may need to run"
		echo >&2 "ERROR: sudo git config --global --add safe.directory \$PWD"
		echo >&2 "ERROR: to trust this git checkout for the root user."
		echo >&2 "ERROR: See https://github.com/atar-axis/xpadneo/issues/346"
		echo >&2
		echo >&2 "HINT: Do not clone forks directly, add them as remotes to your"
		echo >&2 "HINT: original clone. See docs/TESTING.md"
		exit 3
	}
}

__version_lte() {
	[ "$1" = "$(echo -e "$1\n${2/-/.9999-}" | sort -V | head -n1)" ]
}

# shellcheck disable=SC2034
VERSION=$(__version)

DKMS_BIN=$(type -p dkms)

# shellcheck disable=SC2086
: ${DKMS_BIN:?Please install dkms to continue}

get_dkms_versions_installed() {
	${DKMS_BIN} status 2>/dev/null | tr -s ':,/ ' ' ' | awk -- '$1 == "hid-xpadneo" { print $2 }' | sort -nu
}

get_upstream_version_latest() {
	curl -sI "https://github.com/atar-axis/xpadneo/releases/latest" | \
	awk -- 'BEGIN{IGNORECASE=1} /^location:/ { n = split($2, v, /\//); print v[n]; exit }' | \
	tr -d '[:space:]'
}

cat_dkms_make_log() {
	local last_error=$?
	if [ -n "${V[*]}" ]; then
		cat "/var/lib/dkms/hid-xpadneo/${VERSION}/build/make.log" || true
	fi
	exit ${last_error}
}

maybe_already_installed() {
    local last_error=$?
    >&2 echo "HINT: Try uninstalling xpadneo first"
    exit $last_error
}

# shellcheck disable=SC2034
mapfile -t INSTALLED < <(get_dkms_versions_installed)
