#!/bin/sh
# Installs or updates Kolumi Connect:
#   curl -fsSL https://kolumi.app/connect/install.sh | sudo sh
# Optional: KOLUMI_CONNECT_NAME="Living room" sets the display name.
set -eu

BASE_URL=https://kolumi.app/connect
BIN=/usr/local/bin/kolumi-connect
USER_NAME=kolumi-connect
UNIT=/etc/systemd/system/kolumi-connect.service
DEFAULTS=/etc/default/kolumi-connect

say() { printf '%s\n' "kolumi-connect: $*"; }
die() { say "$*" >&2; exit 1; }

detect_arch() {
	case "$(uname -m)" in
	aarch64 | arm64) echo arm64 ;;
	armv7l) echo armv7 ;;
	armv6l) echo armv6 ;;
	x86_64 | amd64) echo amd64 ;;
	*) die "unsupported architecture: $(uname -m)" ;;
	esac
}

fetch() {
	if command -v curl >/dev/null 2>&1; then
		curl -fsSL -o "$2" "$1"
	elif command -v wget >/dev/null 2>&1; then
		wget -q -O "$2" "$1"
	else
		die "curl or wget is required"
	fi
}

install_binary() {
	arch=$(detect_arch)
	tmp=$(mktemp -d)
	trap 'rm -rf "$tmp"' EXIT
	file=kolumi-connect-linux-$arch
	say "downloading $file"
	fetch "$BASE_URL/$file" "$tmp/$file"
	if command -v sha256sum >/dev/null 2>&1; then
		# No silent fallback: a failed checksum download must not turn into an unchecked install.
		fetch "$BASE_URL/SHA256SUMS" "$tmp/SHA256SUMS" 2>/dev/null || die "could not download SHA256SUMS"
		(cd "$tmp" && grep " $file\$" SHA256SUMS | sha256sum -c - >/dev/null 2>&1) || die "checksum mismatch for $file"
	else
		say "sha256sum not found, skipping the checksum check"
	fi
	# Rename over the old binary so a running daemon does not get in the way.
	mkdir -p "$(dirname "$BIN")"
	install -m 0755 -o root -g root "$tmp/$file" "$BIN.new"
	mv -f "$BIN.new" "$BIN"
}

install_mpv() {
	command -v mpv >/dev/null 2>&1 && return 0
	say "installing mpv"
	if command -v apt-get >/dev/null 2>&1; then
		apt-get update -qq
		DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends mpv
	elif command -v dnf >/dev/null 2>&1; then
		dnf install -y mpv
	elif command -v pacman >/dev/null 2>&1; then
		pacman -Sy --noconfirm --needed mpv
	else
		die "no supported package manager; please install mpv and run this again"
	fi
	command -v mpv >/dev/null 2>&1 || die "mpv could not be installed"
}

create_user() {
	getent group audio >/dev/null 2>&1 || groupadd --system audio
	if id "$USER_NAME" >/dev/null 2>&1; then
		usermod -a -G audio "$USER_NAME"
		return 0
	fi
	nologin=$(command -v nologin || echo /bin/false)
	useradd --system --user-group --groups audio --home-dir /var/lib/kolumi-connect --no-create-home --shell "$nologin" "$USER_NAME"
}

write_defaults() {
	if [ -n "${KOLUMI_CONNECT_NAME:-}" ]; then
		umask 022
		tmp_defaults=$DEFAULTS.new
		if [ -f "$DEFAULTS" ]; then
			grep -v '^KOLUMI_CONNECT_NAME=' "$DEFAULTS" >"$tmp_defaults" || true
		else
			: >"$tmp_defaults"
		fi
		escaped=$(printf '%s' "$KOLUMI_CONNECT_NAME" | sed 's/["\\$`]/\\&/g')
		printf 'KOLUMI_CONNECT_NAME="%s"\n' "$escaped" >>"$tmp_defaults"
		mv -f "$tmp_defaults" "$DEFAULTS"
	fi
}

write_unit() {
	cat >"$UNIT" <<'UNIT_EOF'
[Unit]
Description=Kolumi Connect receiver
Documentation=https://kolumi.app/connect
After=network-online.target sound.target
Wants=network-online.target

[Service]
Type=simple
User=kolumi-connect
Group=kolumi-connect
SupplementaryGroups=audio
Environment=KOLUMI_CONNECT_NAME=
EnvironmentFile=-/etc/default/kolumi-connect
ExecStart=/usr/local/bin/kolumi-connect --name=${KOLUMI_CONNECT_NAME}
Restart=always
RestartSec=2
# SIGTERM to the daemon only: it reports progress first, then stops mpv itself.
KillMode=mixed
TimeoutStopSec=20
StateDirectory=kolumi-connect
StateDirectoryMode=0700
UMask=0077
NoNewPrivileges=yes
CapabilityBoundingSet=
AmbientCapabilities=
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
ProtectHostname=yes
ProtectControlGroups=yes
ProtectKernelLogs=yes
ProtectKernelModules=yes
ProtectKernelTunables=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
RestrictNamespaces=yes
RestrictSUIDSGID=yes
RestrictRealtime=yes
LockPersonality=yes
# Audio needs /dev/snd. PrivateDevices, DevicePolicy=closed and ProtectClock
# (it adds a device allow-list) would take it away.

[Install]
WantedBy=multi-user.target
UNIT_EOF
	chmod 0644 "$UNIT"
}

main() {
	[ "$(id -u)" -eq 0 ] || die "please run as root (sudo sh)"
	command -v systemctl >/dev/null 2>&1 || die "systemd is required"
	install_binary
	install_mpv
	create_user
	write_defaults
	write_unit
	systemctl daemon-reload
	systemctl enable kolumi-connect.service >/dev/null 2>&1
	systemctl restart kolumi-connect.service
	say "installed version $("$BIN" version)"
	systemctl --no-pager --full status kolumi-connect.service || true
	say "firewall: allow TCP 47300 and UDP 5353 if the speaker does not appear in the app"
}

# Everything runs from here, so a truncated download cannot run half a script.
main "$@"
