#!/bin/sh
# Offworld Nexus repository installer — https://offworld-nexus.app
#
# Detects this system's package manager and adds the signed Offworld Nexus
# repository (APT, DNF/YUM, Zypper, APK or pacman) together with its key.
#
#   curl -fsSL https://offworld-nexus.app/install.sh | sudo sh
#   curl -fsSL https://offworld-nexus.app/install.sh | sudo sh -s -- --channel nightly
#
# Options:
#   --channel stable|nightly|both   which channel(s) to enable (default: stable)
#   --dry-run                       print every change instead of making it
#   --uninstall                     remove the repository configuration and key
#   -h, --help                      show this help
#
# Signing key fingerprint: E9DD32C63321505EBBCF86386E08120B3306C720
# Generated 2026-11-24. Detached signature: https://offworld-nexus.app/install.sh.asc
set -eu

APT_URL="${OFFWORLD_APT_URL:-https://apt.offworld-nexus.app}"
RPM_URL="${OFFWORLD_RPM_URL:-https://rpm.offworld-nexus.app}"
APK_URL="${OFFWORLD_APK_URL:-https://apk.offworld-nexus.app}"
ARCH_URL="${OFFWORLD_ARCH_URL:-https://arch.offworld-nexus.app}"
FINGERPRINT="E9DD32C63321505EBBCF86386E08120B3306C720"
APK_KEY_NAME="packages@offworld.nexus.rsa.pub"

PKGS_APT="blastit blastit-php-8.3 blastit-php-8.4 blastit-php-8.5 blastit-php-8.6 blastit-python-3.13 blastit-python-3.14 blastit-python-3.15 slipfork tpmd tpmd-backend-keyring tpmd-backend-linux-tpm"
PKGS_RPM="blastit blastit-php-8.3 blastit-php-8.4 blastit-php-8.5 blastit-php-8.6 blastit-python-3.13 blastit-python-3.14 blastit-python-3.15 slipfork"
PKGS_APK="slipfork-0.1.0 slipfork-0.1.1"
PKGS_ARCH="slipfork"

channel="${OFFWORLD_CHANNEL:-stable}"
dry_run=0
action=install

usage() {
	cat <<'EOF'
Offworld Nexus repository installer (https://offworld-nexus.app)
  --channel stable|nightly|both   which channel(s) to enable (default: stable)
  --dry-run                       print every change instead of making it
  --uninstall                     remove the repository configuration and key
EOF
}
say() { printf '==> %s\n' "$*" >&2; }
die() { printf 'offworld-nexus: %s\n' "$*" >&2; exit 1; }

while [ $# -gt 0 ]; do
	case "$1" in
	--channel) shift; channel="${1:-}" ;;
	--channel=*) channel="${1#*=}" ;;
	--nightly) channel=nightly ;;
	--dry-run) dry_run=1 ;;
	--uninstall) action=uninstall ;;
	-h|--help) usage; exit 0 ;;
	*) die "unknown option: $1 (see --help)" ;;
	esac
	shift
done

case "$channel" in
stable|nightly|both) ;;
*) die "--channel must be stable, nightly or both (got '$channel')" ;;
esac

run() {
	if [ "$dry_run" = 1 ]; then printf '+ %s\n' "$*"; else "$@"; fi
}

# write_file PATH MODE < content
write_file() {
	if [ "$dry_run" = 1 ]; then
		printf '+ write %s (mode %s):\n' "$1" "$2"
		sed 's/^/    | /'
		return 0
	fi
	tmp="$1.offworld.$$"
	cat >"$tmp"
	chmod "$2" "$tmp"
	mv -f "$tmp" "$1"
}

remove_file() {
	[ -e "$1" ] || return 0
	run rm -f "$1"
}

need_root() {
	[ "$dry_run" = 1 ] && return 0
	[ "$(id -u)" = 0 ] && return 0
	if [ -f "$0" ] && command -v sudo >/dev/null 2>&1; then
		say "re-running with sudo"
		if [ "$action" = uninstall ]; then
			exec sudo sh "$0" --uninstall
		fi
		exec sudo sh "$0" --channel "$channel"
	fi
	die "run as root: curl -fsSL https://offworld-nexus.app/install.sh | sudo sh"
}

fetch() {
	if command -v curl >/dev/null 2>&1; then
		curl -fsSL --retry 3 "$1"
	elif command -v wget >/dev/null 2>&1; then
		wget -qO- "$1"
	else
		die "neither curl nor wget is installed"
	fi
}

# fetch_key URL DEST: download, check the fingerprint when gpg is available.
fetch_key() {
	if [ "$dry_run" = 1 ]; then printf '+ fetch %s -> %s\n' "$1" "$2"; return 0; fi
	tmp="$2.offworld.$$"
	fetch "$1" >"$tmp" || { rm -f "$tmp"; die "could not download $1"; }
	if command -v gpg >/dev/null 2>&1; then
		got=$(gpg --batch --quiet --with-colons --show-keys "$tmp" 2>/dev/null | grep '^fpr:' | head -n 1 | cut -d: -f10)
		if [ -n "$got" ] && [ "$got" != "$FINGERPRINT" ]; then
			rm -f "$tmp"
			die "unexpected signing key fingerprint $got (expected $FINGERPRINT)"
		fi
	fi
	chmod 0644 "$tmp"
	mv -f "$tmp" "$2"
}

# strip_block FILE: remove a previously written "# BEGIN/END offworld-nexus" block.
strip_block() {
	[ -f "$1" ] || return 0
	grep -q '^# BEGIN offworld-nexus' "$1" || return 0
	if [ "$dry_run" = 1 ]; then printf '+ remove offworld-nexus block from %s\n' "$1"; return 0; fi
	sed '/^# BEGIN offworld-nexus/,/^# END offworld-nexus/d' "$1" >"$1.offworld.$$"
	cat "$1.offworld.$$" >"$1"
	rm -f "$1.offworld.$$"
}

append_block() {
	if [ "$dry_run" = 1 ]; then printf '+ append to %s:\n' "$1"; sed 's/^/    | /'; return 0; fi
	cat >>"$1"
}

detect_family() {
	if [ "$(uname -s)" = Darwin ]; then echo macos; return; fi
	[ -r /etc/os-release ] || { echo unknown; return; }
	# shellcheck disable=SC1091
	. /etc/os-release
	ids=" ${ID:-} ${ID_LIKE:-} "
	case "$ids" in
	*" debian "*|*" ubuntu "*) echo apt ;;
	*" fedora "*|*" rhel "*|*" centos "*|*" rocky "*|*" almalinux "*|*" amzn "*|*" ol "*) echo dnf ;;
	*" suse "*|*" opensuse "*|*" sles "*|*" opensuse-leap "*|*" opensuse-tumbleweed "*) echo zypper ;;
	*" alpine "*) echo apk ;;
	*" arch "*|*" archarm "*|*" manjaro "*|*" endeavouros "*) echo pacman ;;
	*) echo unknown ;;
	esac
}

apt_components() {
	case "$channel" in
	stable) echo main ;;
	nightly) echo nightly ;;
	both) echo "main nightly" ;;
	esac
}

setup_apt() {
	if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
		run apt-get update -qq
		run env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends ca-certificates curl
	fi
	run install -d -m 0755 /etc/apt/keyrings
	fetch_key "$APT_URL/keyring.gpg" /etc/apt/keyrings/offworld-nexus.gpg
	write_file /etc/apt/sources.list.d/offworld-nexus.sources 0644 <<EOF
Types: deb
URIs: $APT_URL
Suites: any-distro
Components: $(apt_components)
Signed-By: /etc/apt/keyrings/offworld-nexus.gpg
EOF
	run apt-get update
	hint="sudo apt install" pkgs="$PKGS_APT"
}

rpm_repo_file() {
	stable_on=0 nightly_on=0
	case "$channel" in stable) stable_on=1 ;; nightly) nightly_on=1 ;; both) stable_on=1 nightly_on=1 ;; esac
	cat <<EOF
[offworld-nexus]
name=Offworld Nexus
baseurl=$RPM_URL/stable/\$basearch/
enabled=$stable_on
gpgcheck=1
repo_gpgcheck=1
gpgkey=$RPM_URL/gpg.key

[offworld-nexus-nightly]
name=Offworld Nexus (nightly)
baseurl=$RPM_URL/nightly/\$basearch/
enabled=$nightly_on
gpgcheck=1
repo_gpgcheck=1
gpgkey=$RPM_URL/gpg.key
EOF
}

# rpm_import: some rpm builds (openSUSE Tumbleweed) cannot import from a URL.
rpm_import() {
	if [ "$dry_run" = 1 ]; then printf '+ rpm --import %s\n' "$RPM_URL/gpg.key"; return 0; fi
	keyfile=$(mktemp)
	fetch_key "$RPM_URL/gpg.key" "$keyfile"
	rpm --import "$keyfile"
	rm -f "$keyfile"
}

setup_dnf() {
	rpm_import
	rpm_repo_file | write_file /etc/yum.repos.d/offworld-nexus.repo 0644
	if command -v dnf >/dev/null 2>&1; then
		run dnf -y makecache --repo offworld-nexus --repo offworld-nexus-nightly
		hint="sudo dnf install"
	else
		run yum -y makecache
		hint="sudo yum install"
	fi
	pkgs="$PKGS_RPM"
}

setup_zypper() {
	rpm_import
	rpm_repo_file | sed 's/^gpgcheck=1$/gpgcheck=1\ntype=rpm-md\nautorefresh=1/' | write_file /etc/zypp/repos.d/offworld-nexus.repo 0644
	run zypper --non-interactive --gpg-auto-import-keys refresh offworld-nexus offworld-nexus-nightly
	hint="sudo zypper install" pkgs="$PKGS_RPM"
}

setup_apk() {
	run mkdir -p /etc/apk/keys
	if [ "$dry_run" = 1 ]; then
		printf '+ fetch %s -> %s\n' "$APK_URL/$APK_KEY_NAME" "/etc/apk/keys/$APK_KEY_NAME"
	else
		fetch "$APK_URL/$APK_KEY_NAME" >"/etc/apk/keys/$APK_KEY_NAME"
	fi
	strip_block /etc/apk/repositories
	{
		echo "# BEGIN offworld-nexus"
		case "$channel" in stable|both) echo "$APK_URL/stable" ;; esac
		case "$channel" in nightly|both) echo "$APK_URL/nightly" ;; esac
		echo "# END offworld-nexus"
	} | append_block /etc/apk/repositories
	run apk update
	hint="apk add" pkgs="$PKGS_APK"
}

setup_pacman() {
	if [ "$dry_run" = 1 ]; then
		printf '+ pacman-key --add <(%s) && pacman-key --lsign-key %s\n' "$ARCH_URL/gpg.key" "$FINGERPRINT"
	else
		# A fresh install has no local master key yet, and --lsign-key needs one.
		if ! pacman-key --list-secret-keys 2>/dev/null | grep -q '^sec'; then
			pacman-key --init
		fi
		keyfile=$(mktemp)
		fetch_key "$ARCH_URL/gpg.key" "$keyfile"
		pacman-key --add "$keyfile"
		rm -f "$keyfile"
		pacman-key --lsign-key "$FINGERPRINT"
	fi
	strip_block /etc/pacman.conf
	{
		echo "# BEGIN offworld-nexus"
		case "$channel" in stable|both) printf '[offworld]\nServer = %s/stable/$arch\n' "$ARCH_URL" ;; esac
		case "$channel" in nightly|both) printf '[offworld-nightly]\nServer = %s/nightly/$arch\n' "$ARCH_URL" ;; esac
		echo "# END offworld-nexus"
	} | append_block /etc/pacman.conf
	run pacman -Sy --noconfirm
	hint="sudo pacman -S" pkgs="$PKGS_ARCH"
}

uninstall() {
	remove_file /etc/apt/sources.list.d/offworld-nexus.sources
	remove_file /etc/apt/keyrings/offworld-nexus.gpg
	remove_file /etc/yum.repos.d/offworld-nexus.repo
	remove_file /etc/zypp/repos.d/offworld-nexus.repo
	remove_file "/etc/apk/keys/$APK_KEY_NAME"
	strip_block /etc/apk/repositories
	strip_block /etc/pacman.conf
	say "Offworld Nexus repository configuration removed. Installed packages were left alone."
}

need_root

if [ "$action" = uninstall ]; then
	uninstall
	exit 0
fi

family=$(detect_family)
hint="" pkgs=""
case "$family" in
apt) setup_apt ;;
dnf) setup_dnf ;;
zypper) setup_zypper ;;
apk) setup_apk ;;
pacman) setup_pacman ;;
macos)
	say "macOS: Offworld Nexus software is distributed through Homebrew where available."
	say "See https://offworld-nexus.app for each project's install instructions."
	exit 0
	;;
*)
	die "unsupported system; see https://offworld-nexus.app for manual instructions"
	;;
esac

say "Offworld Nexus repository ready ($family, channel: $channel)."
if [ -n "$pkgs" ]; then
	say "Available packages: $pkgs"
	say "Install one with: $hint <package>"
fi
