#!/bin/bash
# FINEMINE launcher starter for Linux and macOS, the counterpart of the Windows Prestarter: on the first run it downloads
# a Java runtime with JavaFX (BellSoft Liberica JRE 25 Full like the Windows one, mirrored on finemine.su) and the launcher, then starts it;
# later runs start the launcher right away (the launcher keeps itself up to date).
#   Linux:  bash FINEMINE.sh    or    curl -fsSL https://finemine.su/FINEMINE.sh | bash
#           (the first run also adds FINEMINE to the applications menu)
#           Packaged as FINEMINE.deb / FINEMINE.rpm it lives in /opt/finemine with a system menu entry.
#   macOS:  this script is the executable of FINEMINE.app (installed by FINEMINE.pkg); it also works from the Terminal.
# Written for bash 3.2 (the one macOS ships). Everything runs from main() at the very end, so a partly
# downloaded script never runs.

SITE="https://finemine.su"
JAVA_VERSION="25.0.4.1+1"
FFMPEG_VERSION="7.1.5"
MIRROR="$SITE/launcher-runtime"
UPSTREAM="https://github.com/bell-sw/Liberica/releases/download/$JAVA_VERSION"

say() {
	printf 'FINEMINE: %s\n' "$*" >&2
}

# Desktop dialogs get the Russian texts as arguments, which GLib/Qt refuse to parse under a non-UTF-8 locale
# (a bare system, a session without LANG): such dialogs run with C.UTF-8
dialog_locale() {
	case "$(locale charmap 2>/dev/null)" in
		UTF-8 | utf8) ;;
		*) export LC_ALL=C.UTF-8 ;;
	esac
}

# Shows the error in a window too when there is no terminal (started from the .app or the applications menu)
fail() {
	progress_abort
	say "ошибка: $*"
	if [ "$OS" = Darwin ]; then
		osascript -e "display dialog \"$*\" with title \"FINEMINE\" buttons {\"OK\"} default button 1 with icon stop" >/dev/null 2>&1
	elif [ ! -t 2 ]; then
		dialog_locale
		if command -v zenity >/dev/null 2>&1; then
			zenity --error --title=FINEMINE --text="$*" >/dev/null 2>&1
		elif command -v kdialog >/dev/null 2>&1; then
			kdialog --title FINEMINE --error "$*" >/dev/null 2>&1
		elif command -v notify-send >/dev/null 2>&1; then
			notify-send FINEMINE "$*" >/dev/null 2>&1
		fi
	fi

	exit 1
}

# Progress of the first-run downloads, shown only when there is no terminal (a terminal gets curl's own bar):
# on macOS the FINEMINE window (ui_page / ui_script below, a WebKit page in a native window), on Linux the desktop's
# progress dialog (zenity, or kdialog on KDE). The window follows a status file of one line "stage|label|path|total",
# stage being download, unpack or done; it measures the downloading file itself.
PROGRESS_FILE=""
PROGRESS_PID=""

# progress STAGE LABEL [FILE TOTAL]
progress() {
	[ -t 2 ] && return
	if [ -z "$PROGRESS_FILE" ]; then
		PROGRESS_FILE="$HOME_DIR/.progress"
		progress_write "$@"
		progress_window
	else
		progress_write "$@"
	fi
}

progress_write() {
	printf '%s|%s|%s|%s\n' "$1" "$2" "${3:-}" "${4:-0}" >"$PROGRESS_FILE.tmp" && mv -f "$PROGRESS_FILE.tmp" "$PROGRESS_FILE"
}

# The window shows "done" for a moment and closes by itself
progress_done() {
	[ -n "$PROGRESS_FILE" ] && progress_write done "$1"
}

progress_abort() {
	if [ -n "$PROGRESS_FILE" ]; then
		rm -f "$PROGRESS_FILE"
		PROGRESS_FILE=""
	fi
}

progress_window() {
	if [ "$OS" = Darwin ]; then
		mkdir -p "$HOME_DIR/ui"
		ui_page >"$HOME_DIR/ui/progress.html"
		ui_script >"$HOME_DIR/ui/progress.js"
		osascript -l JavaScript "$HOME_DIR/ui/progress.js" "$PROGRESS_FILE" "$HOME_DIR/ui/progress.html" >/dev/null 2>&1 &
		PROGRESS_PID=$!
		sleep 1
		kill -0 "$PROGRESS_PID" 2>/dev/null && return
		# The window could not open (very old macOS?): at least say what is going on
		osascript -e 'display dialog "Первый запуск: скачиваю Java для лаунчера (около 140 МБ). Лаунчер откроется сам." with title "FINEMINE" buttons {"Скрыть"} default button 1 giving up after 1800' >/dev/null 2>&1 &
	elif command -v zenity >/dev/null 2>&1; then
		(
			dialog_locale
			progress_feed | zenity --progress --title=FINEMINE --text="Подготовка…" --percentage=0 --auto-close --no-cancel --width=460 >/dev/null 2>&1
		) &
	elif command -v kdialog >/dev/null 2>&1; then
		(
			dialog_locale
			progress_feed | progress_kdialog >/dev/null 2>&1
		) &
	elif command -v notify-send >/dev/null 2>&1; then
		(
			dialog_locale
			notify-send -i "$HOME_DIR/icon.png" FINEMINE "Первый запуск: скачиваю Java для лаунчера. Лаунчер откроется сам." >/dev/null 2>&1
		)
	fi
}

# Linux: turns the status file into the zenity protocol, a percentage line and a "# text" line every 0.3 s
progress_feed() {
	local stage label path total size last=-1 stamp=0 now speed=0
	while :; do
		IFS='|' read -r stage label path total <"$PROGRESS_FILE" 2>/dev/null || break
		case "$stage" in
			download)
				size=$(stat -c %s "$path" 2>/dev/null || echo 0)
				now=$(date +%s%N)
				if [ "$last" -ge 0 ] && [ "$size" -ge "$last" ] && [ "$now" -gt "$stamp" ]; then
					speed=$(((speed * 3 + (size - last) * 1000000000 / (now - stamp)) / 4))
				else
					speed=0
				fi
				last=$size
				stamp=$now
				awk -v s="$size" -v t="$total" -v v="$speed" -v l="$label" 'BEGIN {
					mb = 1048576
					if (t > 0) { p = int(s * 100 / t); if (p > 99) p = 99; print p } else print 0
					text = l
					if (t > 0) text = text sprintf(": %d из %d МБ", s / mb, t / mb)
					if (v > 0) {
						text = text sprintf(" · %.1f МБ/с", v / mb)
						if (t > s) { left = (t - s) / v; text = text (left < 60 ? sprintf(" · ≈ %d с", left + 1) : sprintf(" · ≈ %d мин", left / 60 + 1)) }
					}
					gsub(/\./, ",", text)
					print "# " text
				}'
				;;
			unpack)
				echo 99
				echo "# $label"
				last=-1
				;;
			done)
				echo 100
				echo "# $label"
				return
				;;
		esac
		sleep 0.3
	done
	echo 100
}

# KDE without zenity: drives a kdialog progress bar over D-Bus with the same feed
progress_kdialog() {
	local ref qdbus line
	ref=$(kdialog --title FINEMINE --progressbar "Подготовка…" 100) || return
	for qdbus in qdbus qdbus6 qdbus-qt6 qdbus-qt5; do
		command -v "$qdbus" >/dev/null 2>&1 && break
		qdbus=""
	done

	while IFS= read -r line; do
		if [ -n "$qdbus" ]; then
			case "$line" in
				'# '*) $qdbus $ref setLabelText "${line#\# }" ;;
				*) $qdbus $ref Set "" value "$line" ;;
			esac
		else
			case "$line" in
				'# '*) gdbus call --session --dest "${ref% *}" --object-path "${ref#* }" --method org.kde.kdialog.ProgressDialog.setLabelText "${line#\# }" ;;
				*) gdbus call --session --dest "${ref% *}" --object-path "${ref#* }" --method org.freedesktop.DBus.Properties.Set org.kde.kdialog.ProgressDialog value "<$line>" ;;
			esac
		fi
	done

	if [ -n "$qdbus" ]; then
		$qdbus $ref close
	else
		gdbus call --session --dest "${ref% *}" --object-path "${ref#* }" --method org.kde.kdialog.ProgressDialog.close
	fi
}

# fetch URL FILE [SIZE]: downloads with a progress bar in a terminal, quietly otherwise. A partial FILE left by an
# interrupted run is continued (the callers verify the result); with SIZE known, a FILE of that size counts as done.
fetch() {
	local have=0 expected="${3:-0}"
	[ -f "$2" ] && have=$(file_size "$2")
	if [ "$expected" -gt 0 ]; then
		[ "$have" -eq "$expected" ] && return 0
		[ "$have" -gt "$expected" ] && rm -f "$2"
	fi

	if command -v curl >/dev/null 2>&1; then
		local quiet="-sS"
		[ -t 2 ] && quiet="--progress-bar"
		curl -fL --retry 3 --connect-timeout 20 $quiet -C - -o "$2" "$1" && return 0
		# The server could not continue the file: start over
		rm -f "$2"
		curl -fL --retry 3 --connect-timeout 20 $quiet -o "$2" "$1"
	elif command -v wget >/dev/null 2>&1; then
		wget -q -c -T 20 -O "$2" "$1" && return 0
		rm -f "$2"
		wget -q -T 20 -O "$2" "$1"
	else
		fail "Для загрузки нужен curl или wget. Установите один из них и запустите снова."
	fi
}

file_size() {
	stat -c %s "$1" 2>/dev/null || stat -f %z "$1" 2>/dev/null || echo 0
}

# A complete zip (the launcher jar): starts with a local file header and ends with the end-of-central-directory record
zip_complete() {
	[ -s "$1" ] && [ "$(head -c 2 "$1")" = PK ] && [ "$(tail -c 22 "$1" | head -c 4 | od -An -tx1 | tr -d ' \n')" = 504b0506 ]
}

# Size of a remote file in bytes, 0 if unknown
remote_size() {
	command -v curl >/dev/null 2>&1 || {
		echo 0
		return
	}
	curl -fsSIL --connect-timeout 10 "$1" 2>/dev/null | tr -d '\r' | awk 'tolower($1) == "content-length:" { size = $2 } END { print size + 0 }'
}

sha256() {
	if command -v sha256sum >/dev/null 2>&1; then
		sha256sum "$1" | cut -d ' ' -f 1
	else
		shasum -a 256 "$1" | cut -d ' ' -f 1
	fi
}

# Picks the runtime archive for this system and architecture
platform() {
	local arch
	case "$OS" in
		Linux) PLATFORM=linux ;;
		Darwin) PLATFORM=macos ;;
		*) fail "Эта система не поддерживается ($OS). Скачайте .jar-версию лаунчера с finemine.su." ;;
	esac

	arch=$(uname -m)
	# A Mac with Apple Silicon reports x86_64 to programs running under Rosetta: prefer the native runtime
	if [ "$OS" = Darwin ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" = 1 ]; then
		arch=arm64
	fi

	case "$arch" in
		x86_64 | amd64) ARCH=amd64 ;;
		aarch64 | arm64) ARCH=aarch64 ;;
		*) fail "Процессор $arch не поддерживается. Скачайте .jar-версию лаунчера с finemine.su и установите Java вручную." ;;
	esac

	FILE="bellsoft-jre$JAVA_VERSION-$PLATFORM-$ARCH-full.tar.gz"
	case "$PLATFORM-$ARCH" in
		linux-amd64) SHA=9ade2b638ffe81a632a058ddc22347487497d6f705c8ccbc42fee7bf835d5dd3; SIZE=143747039 ;;
		linux-aarch64) SHA=af0d78c4f2e75cdcb2adab1eb4fff61924407642466b5c8d8f6249aa059775f9; SIZE=147346919 ;;
		macos-amd64) SHA=e7f01d133b488e57894b655e7ea7f2dfa11543ed63ea7b7958b02fd9d06dd137; SIZE=128984528 ;;
		macos-aarch64) SHA=e4b6a441215f850b9ea747baed1f99e50f00789243e0dec3c428607c1f7dc293; SIZE=126029993 ;;
	esac
}

find_java() {
	if [ "$OS" = Darwin ] && mac_bundle; then
		JAVA="$RUNTIME/FINEMINE.app/Contents/MacOS/java"
	else
		JAVA=$(find "$RUNTIME" -type f -path '*/bin/java' 2>/dev/null | head -n 1)
	fi
	[ -n "$JAVA" ] && "$JAVA" -version >/dev/null 2>&1
}

# macOS shows a process by the app bundle its executable lies in: a bare runtime runs as "java" with the generic
# "exec" icon. So the runtime becomes FINEMINE.app whose executable is java itself (Contents/MacOS), with the name and
# icon of FINEMINE. The launcher restarts itself through java.home/bin/java, so Contents/bin/java is a wrapper that
# execs Contents/MacOS/java: the restarted launcher, the window the player sees, runs from the bundle as well.
# A runtime unpacked earlier is rearranged in place; if this macOS does not run it so, it is put back as it was.
mac_bundle() {
	local app="$RUNTIME/FINEMINE.app" jre icon
	[ -x "$app/Contents/MacOS/java" ] && [ -x "$app/Contents/bin/java" ] && return 0
	jre=$(find "$RUNTIME" -maxdepth 3 -type f -path '*/bin/java' ! -path '*/FINEMINE.app/*' 2>/dev/null | head -n 1)
	[ -n "$jre" ] || return 1
	jre=$(dirname "$(dirname "$jre")")

	rm -rf "$app"
	mkdir -p "$app/Contents" || return 1
	mv "$jre"/* "$app/Contents/" && rm -rf "$jre" || return 1
	mv "$app/Contents/bin" "$app/Contents/MacOS" && mkdir "$app/Contents/bin" || return 1
	printf '%s\n' '#!/bin/sh' 'dir=$(cd "$(dirname "$0")/../MacOS" && pwd -P) && exec "$dir/java" "$@"' >"$app/Contents/bin/java" && chmod 755 "$app/Contents/bin/java"
	mkdir -p "$app/Contents/Resources"
	icon="$(cd "$(dirname "$0")" 2>/dev/null && pwd)/../Resources/finemine.icns"
	if [ -f "$icon" ]; then
		cp "$icon" "$app/Contents/Resources/finemine.icns"
	else
		fetch "$MIRROR/finemine.icns" "$app/Contents/Resources/finemine.icns" >/dev/null 2>&1
	fi
	cat >"$app/Contents/Info.plist" <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleName</key>
	<string>FINEMINE</string>
	<key>CFBundleDisplayName</key>
	<string>FINEMINE</string>
	<key>CFBundleIdentifier</key>
	<string>su.finemine.launcher</string>
	<key>CFBundleExecutable</key>
	<string>java</string>
	<key>CFBundleIconFile</key>
	<string>finemine</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>LSMinimumSystemVersion</key>
	<string>10.15</string>
	<key>NSHighResolutionCapable</key>
	<true/>
</dict>
</plist>
EOF

	if "$app/Contents/MacOS/java" -version >/dev/null 2>&1; then
		return 0
	fi

	rm -rf "$app/Contents/bin"
	mv "$app/Contents/MacOS" "$app/Contents/bin"
	rm -f "$app/Contents/Info.plist"
	return 1
}

# Downloads the runtime from the mirror (GitHub as a fallback), checks it and unpacks it; older runtimes are removed
install_java() {
	local part="$HOME_DIR/runtime/$FILE.part" url
	mkdir -p "$HOME_DIR/runtime" || fail "Не удалось создать папку $HOME_DIR"
	# The mirror first, continuing what an interrupted run left; then the mirror from scratch; then GitHub
	for url in "$MIRROR/$FILE" "$MIRROR/$FILE" "$UPSTREAM/$FILE"; do
		say "скачиваю Java $JAVA_VERSION ($PLATFORM $ARCH)..."
		progress download "Скачиваю Java для лаунчера" "$part" "$SIZE"
		if fetch "$url" "$part" "$SIZE" && [ "$(sha256 "$part")" = "$SHA" ]; then
			break
		fi

		say "не получилось с $url"
		rm -f "$part"
	done

	[ -f "$part" ] || fail "Не удалось скачать Java. Проверьте интернет и запустите снова."

	progress unpack "Распаковываю Java"
	rm -rf "$RUNTIME"
	mkdir -p "$RUNTIME" && tar -xzf "$part" -C "$RUNTIME" || {
		rm -f "$part"
		fail "Не удалось распаковать Java (нет места на диске?)."
	}
	rm -f "$part"
	# Downloads by curl are not quarantined, but make sure Gatekeeper never stops the runtime on a Mac
	[ "$OS" = Darwin ] && xattr -dr com.apple.quarantine "$RUNTIME" >/dev/null 2>&1

	local old
	for old in "$HOME_DIR"/runtime/jre-*; do
		[ "$old" != "$RUNTIME" ] && rm -rf "$old"
	done
}

# Linux: JavaFX plays the launcher's music through ffmpeg (libavcodec 54..61) and the launcher does not start
# without it. If the system has none of those, a self-contained ffmpeg 7.1 (LGPL build by BtbN, mirrored on
# finemine.su) is downloaded next to the runtime and put on the library path. FINEMINE_SKIP_MEDIA_CHECK=1 skips this.
system_ffmpeg() {
	local found="" ldconfig v
	for ldconfig in ldconfig /sbin/ldconfig /usr/sbin/ldconfig; do
		if command -v "$ldconfig" >/dev/null 2>&1; then
			found=$("$ldconfig" -p 2>/dev/null | grep -o 'libavcodec\.so\.[0-9]*' | sort -u)
			break
		fi
	done
	if [ -z "$found" ]; then
		found=$(ls /usr/lib/libavcodec.so.* /usr/lib64/libavcodec.so.* /usr/lib/*/libavcodec.so.* 2>/dev/null | grep -o 'libavcodec\.so\.[0-9]*' | sort -u)
	fi

	for v in 54 56 57 58 59 60 61; do
		printf '%s\n' "$found" | grep -qx "libavcodec\.so\.$v" && return 0
	done

	return 1
}

ffmpeg_libs() {
	[ -n "${FINEMINE_SKIP_MEDIA_CHECK:-}" ] && return
	system_ffmpeg && return

	local name="ffmpeg-$FFMPEG_VERSION-linux-$ARCH" sha size
	local dir="$HOME_DIR/$name" part="$HOME_DIR/$name.tar.gz.part"
	case "$ARCH" in
		amd64) sha=44a632590043ee60dd039a38ca6426359f2e7746cfb2d2af9e9d581e164f36d0; size=41921256 ;;
		aarch64) sha=5ff93b1ae921431a3c34dd28ad2af63cf4f68fe7d2faf8309a5f424dff648220; size=38800660 ;;
	esac

	if [ ! -f "$dir/libavcodec.so.61" ]; then
		say "скачиваю ffmpeg для звука лаунчера..."
		rm -rf "$dir"
		progress download "Скачиваю звуковые библиотеки" "$part" "$size"
		fetch "$MIRROR/$name.tar.gz" "$part" "$size" && [ "$(sha256 "$part")" = "$sha" ] && tar -xzf "$part" -C "$HOME_DIR" || {
			rm -rf "$dir" "$part"
			fail "Не удалось скачать библиотеки звука для лаунчера. Проверьте интернет и запустите снова."
		}
		rm -f "$part"

		local old
		for old in "$HOME_DIR"/ffmpeg-*; do
			[ "$old" != "$dir" ] && rm -rf "$old"
		done
	fi

	export LD_LIBRARY_PATH="$dir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
}

# Linux: keep a copy of this script and an icon, and put FINEMINE into the applications menu
# (not needed when the .deb/.rpm package installed it system-wide)
desktop_entry() {
	[ -f /usr/share/applications/finemine.desktop ] && return
	local apps="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
	if [ -f "$0" ] && grep -q 'FINEMINE launcher starter' "$0" 2>/dev/null; then
		[ "$0" -ef "$HOME_DIR/FINEMINE.sh" ] || cp "$0" "$HOME_DIR/FINEMINE.sh"
	elif [ ! -f "$HOME_DIR/FINEMINE.sh" ]; then
		fetch "$SITE/FINEMINE.sh" "$HOME_DIR/FINEMINE.sh" || return
	fi

	[ -f "$HOME_DIR/icon.png" ] || fetch "$MIRROR/finemine.png" "$HOME_DIR/icon.png" || true
	mkdir -p "$apps" || return
	cat >"$apps/finemine.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=FINEMINE
Comment=Лаунчер серверов FINEMINE
Exec=bash "$HOME_DIR/FINEMINE.sh"
Icon=$HOME_DIR/icon.png
Terminal=false
Categories=Game;
EOF
}

# One starter at a time: a second launch while the first one is still downloading (double clicks, an impatient
# relaunch) leaves it alone instead of writing over the same files. Released right before the launcher starts.
LOCK=""
lock() {
	local pid
	LOCK="$HOME_DIR/.lock"
	if ! mkdir "$LOCK" 2>/dev/null; then
		pid=$(cat "$LOCK/pid" 2>/dev/null)
		if lock_holder "$pid"; then
			say "уже запущен и скачивает, подождите"
			LOCK=""
			exit 0
		fi

		rm -rf "$LOCK"
		mkdir "$LOCK" 2>/dev/null || {
			LOCK=""
			return
		}
	fi

	echo $$ >"$LOCK/pid"
	trap unlock EXIT
}

# Whether the starter that took the lock is still at work: a live (not zombie) bash running this script, and a lock
# younger than an hour, so a lock left by a killed run never blocks the starter after its process id gets reused
lock_holder() {
	[ -n "$1" ] && [ "$1" != $$ ] && kill -0 "$1" 2>/dev/null || return 1
	case "$(ps -o stat= -p "$1" 2>/dev/null)" in
		Z*) return 1 ;;
	esac
	ps -o command= -p "$1" 2>/dev/null | grep -q -E 'FINEMINE|bash' || return 1
	[ -n "$(find "$LOCK" -maxdepth 0 -mmin -60 2>/dev/null)" ]
}

unlock() {
	[ -n "$LOCK" ] && rm -rf "$LOCK"
	LOCK=""
}

# The macOS progress window: its page and the JavaScript for Automation that shows it in a native window
ui_page() {
	cat <<'FINEMINE_PAGE'
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>FINEMINE</title>
<style>
	:root {
		--bg: #0b0d18;
		--text: #f5f5f7;
		--muted: rgba(235, 235, 245, 0.68);
		--track: rgba(255, 255, 255, 0.09);
		--magenta: #ff2bd6;
		--cyan: #22e5f0;
		--violet: #ab06a1;
		--teal: #209c9e;
		color-scheme: dark;
	}

	* {
		box-sizing: border-box;
	}

	html, body {
		height: 100%;
		margin: 0;
		overflow: hidden;
		user-select: none;
		-webkit-user-select: none;
		cursor: default;
	}

	body {
		font: 13px/1.4 -apple-system, BlinkMacSystemFont, "SF Pro Text", Inter, "Segoe UI", sans-serif;
		color: var(--text);
		background:
			radial-gradient(120% 90% at 0% 0%, rgba(171, 6, 161, 0.32), transparent 55%),
			radial-gradient(120% 100% at 100% 100%, rgba(32, 156, 158, 0.30), transparent 60%),
			var(--bg);
		-webkit-font-smoothing: antialiased;
	}

	/* A faint grid, like the HUD of the site, fading towards the bottom */
	body::before {
		content: "";
		position: fixed;
		inset: 0;
		background-image:
			linear-gradient(rgba(255, 255, 255, 0.035) 1px, transparent 1px),
			linear-gradient(90deg, rgba(255, 255, 255, 0.035) 1px, transparent 1px);
		background-size: 22px 22px;
		mask-image: linear-gradient(#000, transparent 85%);
		-webkit-mask-image: linear-gradient(#000, transparent 85%);
		pointer-events: none;
	}

	main {
		position: relative;
		padding: 40px 28px 24px;
	}

	header {
		display: flex;
		align-items: center;
		gap: 14px;
	}

	.logo {
		width: 48px;
		height: 48px;
		flex: none;
		filter: drop-shadow(0 0 10px rgba(255, 43, 214, 0.35)) drop-shadow(0 0 14px rgba(34, 229, 240, 0.25));
	}

	h1 {
		margin: 0;
		font-size: 15px;
		font-weight: 600;
		letter-spacing: -0.01em;
	}

	#stage {
		margin-top: 2px;
		color: var(--muted);
		transition: opacity 0.2s ease-out;
	}

	.bar {
		position: relative;
		height: 8px;
		margin-top: 22px;
		border-radius: 999px;
		background: var(--track);
		overflow: hidden;
	}

	.fill {
		position: absolute;
		inset: 0 auto 0 0;
		width: 0;
		border-radius: inherit;
		background: linear-gradient(90deg, var(--magenta), var(--cyan));
		box-shadow: 0 0 12px rgba(255, 43, 214, 0.55), 0 0 16px rgba(34, 229, 240, 0.35);
		/* Linear: the download goes at a steady rate, the bar should too */
		transition: width 0.3s linear;
	}

	/* A soft highlight sweeping over the filled part while it grows */
	.fill::after {
		content: "";
		position: absolute;
		inset: 0;
		background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.45), transparent);
		transform: translateX(-100%);
		animation: sweep 1.8s ease-in-out infinite;
	}

	@keyframes sweep {
		to {
			transform: translateX(100%);
		}
	}

	/* Unknown size or unpacking: a moving segment instead of a percentage */
	.bar.busy .fill {
		width: 32% !important;
		transition: none;
		animation: busy 1.3s ease-in-out infinite;
	}

	@keyframes busy {
		from {
			left: -32%;
		}
		to {
			left: 100%;
		}
	}

	.meta {
		display: flex;
		justify-content: space-between;
		margin-top: 10px;
		color: var(--muted);
		font-size: 12px;
		font-variant-numeric: tabular-nums;
	}

	#amount {
		color: var(--text);
	}

	body.done #stage {
		color: var(--cyan);
	}

	body.leaving main {
		opacity: 0;
		transform: translateY(-4px);
		transition: opacity 0.18s ease-in, transform 0.18s ease-in;
	}

	@media (prefers-reduced-motion: reduce) {
		.fill {
			transition: none;
		}

		.fill::after {
			animation: none;
			display: none;
		}

		.bar.busy .fill {
			animation: none;
			left: 0;
			width: 100% !important;
			opacity: 0.5;
		}

		body.leaving main {
			transition: none;
		}
	}
</style>
</head>
<body>
<main role="status" aria-live="polite">
	<header>
		<img class="logo" alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAY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XRBg2pZuzg+jnn+OQKfXn+f7gQtOFRh5wHwzczvZIO/m2sZfv6uk932dYYSsEw6a0OyaIHD+OQyasmKt3yw0vI8E3kW8u7vnevp9fnl/UrBS8nB3wg0gr0taGQqaMm+a98PE0PsTtSNAXS1mxDhy0nXzP11fylBPd0e4oDBzqoQDuh/1rygCryRIjAQreUwG0t98N+9WUEfzsIAGDd1sA8fb222F/mjKEF0EYhp+tAKIdHVNgP5oyhr8coGsMqQKo2O/qBZ2ucNf4bAXA9/ypcDlNgLCiVi1VABX/Rc1KQX6ApBYAP+C7AbbTBBgrYtXJAtBX8lQoVsiqC/UYN8LpGo1Go9FoNBqNRqPRaDRB5P/0D8cwX+h9vgAAAABJRU5ErkJggg==">
		<div>
			<h1>Первый запуск FINEMINE</h1>
			<div id="stage">Подготовка…</div>
		</div>
	</header>
	<div class="bar" id="bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
		<div class="fill" id="fill"></div>
	</div>
	<div class="meta">
		<span id="amount">&nbsp;</span>
		<span id="rate">&nbsp;</span>
	</div>
</main>
<script>
	// Filled in by the starter: update({stage, label, done, total, speed}); sizes in bytes, speed in bytes per second
	const mb = (bytes) => (bytes / 1048576).toLocaleString("ru-RU", {maximumFractionDigits: bytes < 10 * 1048576 ? 1 : 0});

	function eta(seconds) {
		if (!isFinite(seconds) || seconds <= 0) {
			return "";
		}

		if (seconds < 60) {
			return "≈ " + Math.max(1, Math.round(seconds)) + " с";
		}

		const m = Math.floor(seconds / 60), s = Math.round(seconds % 60);
		return "≈ " + m + " мин" + (s ? " " + s + " с" : "");
	}

	function update(state) {
		const bar = document.getElementById("bar"), fill = document.getElementById("fill");
		document.getElementById("stage").textContent = state.label;
		document.body.classList.toggle("done", state.stage === "done");
		const known = state.stage === "download" && state.total > 0;
		bar.classList.toggle("busy", !known && state.stage !== "done");
		if (state.stage === "done") {
			fill.style.width = "100%";
			bar.setAttribute("aria-valuenow", "100");
			document.getElementById("amount").textContent = "";
			document.getElementById("rate").textContent = "";
			return;
		}

		if (known) {
			const k = Math.min(1, state.done / state.total);
			fill.style.width = (k * 100).toFixed(1) + "%";
			bar.setAttribute("aria-valuenow", String(Math.round(k * 100)));
			document.getElementById("amount").textContent = mb(state.done) + " из " + mb(state.total) + " МБ";
			const speed = state.speed > 0 ? mb(state.speed) + " МБ/с" : "";
			const left = state.speed > 0 ? eta((state.total - state.done) / state.speed) : "";
			document.getElementById("rate").textContent = [speed, left].filter(Boolean).join(" · ");
		} else {
			document.getElementById("amount").textContent = state.stage === "unpack" ? "Почти готово" : "";
			document.getElementById("rate").textContent = "";
		}
	}

	function leave() {
		document.body.classList.add("leaving");
	}

	// Preview: progress.html#{"stage":"download",...}
	if (location.hash.length > 1) {
		update(JSON.parse(decodeURIComponent(location.hash.slice(1))));
	}
</script>
</body>
</html>
FINEMINE_PAGE
}

ui_script() {
	cat <<'FINEMINE_SCRIPT'
// FINEMINE starter progress window for macOS (JavaScript for Automation, run by osascript -l JavaScript):
// a small borderless-looking window showing progress.html in a WKWebView. The starter writes its state into a status
// file, one line "stage|label|path|total" (stage: download, unpack, done); this script watches the size of the file
// being downloaded, smooths the speed and pushes everything into the page. It closes itself after "done", or when
// the status file disappears (the starter went away).
// Usage: osascript -l JavaScript progress.js STATUS_FILE PAGE_FILE
ObjC.import('Cocoa');
ObjC.import('WebKit');
ObjC.import('stdlib');

var WIDTH = 440, HEIGHT = 190;
var TITLED = 1, FULL_SIZE_CONTENT = 1 << 15, BUFFERED = 2, TITLE_HIDDEN = 1, FLOATING = 3, ACCESSORY = 1;

var web, win, statusFile;
var lastSize = -1, lastTime = 0, speed = 0, closingIn = -1;

function read(path) {
	var text = $.NSString.stringWithContentsOfFileEncodingError($(path), $.NSUTF8StringEncoding, null);
	return text.isNil() ? null : ObjC.unwrap(text);
}

function fileSize(path) {
	var attributes = $.NSFileManager.defaultManager.attributesOfItemAtPathError($(path), null);
	if (attributes.isNil()) {
		return 0;
	}

	var size = attributes.objectForKey($('NSFileSize'));
	return size.isNil() ? 0 : ObjC.unwrap(size);
}

function push(state) {
	web.evaluateJavaScriptCompletionHandler($('update(' + JSON.stringify(state) + ')'), null);
}

function tick() {
	if (closingIn >= 0) {
		closingIn--;
		if (closingIn === 2) {
			web.evaluateJavaScriptCompletionHandler($('leave()'), null);
		}

		if (closingIn === 0) {
			$.exit(0);
		}

		return;
	}

	var text = read(statusFile);
	if (text === null) {
		$.exit(0);
	}

	var parts = text.replace(/\n+$/, '').split('|');
	var state = {stage: parts[0], label: parts[1] || '', done: 0, total: Number(parts[3]) || 0, speed: 0};
	if (state.stage === 'download') {
		state.done = fileSize(parts[2] || '');
		var now = Date.now() / 1000;
		if (lastSize >= 0 && state.done >= lastSize && now > lastTime) {
			// Exponential smoothing, so the speed and the time left do not jump around
			var current = (state.done - lastSize) / (now - lastTime);
			speed = speed > 0 ? speed * 0.85 + current * 0.15 : current;
		} else if (state.done < lastSize) {
			speed = 0; // a new file started
		}

		lastSize = state.done;
		lastTime = now;
		state.speed = speed;
	} else {
		lastSize = -1;
		speed = 0;
	}

	push(state);
	if (state.stage === 'done') {
		closingIn = 5; // show "done" for a moment, then fade out
	}
}

ObjC.registerSubclass({
	name: 'FMProgressTicker',
	superclass: 'NSObject',
	methods: {
		'tick:': {
			types: ['void', ['id']],
			implementation: function (timer) {
				tick();
			}
		}
	}
});

function run(argv) {
	statusFile = argv[0];
	var page = argv[1];
	var app = $.NSApplication.sharedApplication;
	app.setActivationPolicy(ACCESSORY);

	win = $.NSWindow.alloc.initWithContentRectStyleMaskBackingDefer($.NSMakeRect(0, 0, WIDTH, HEIGHT), TITLED | FULL_SIZE_CONTENT, BUFFERED, false);
	win.title = $('FINEMINE');
	win.titlebarAppearsTransparent = true;
	win.titleVisibility = TITLE_HIDDEN;
	win.movableByWindowBackground = true;
	win.backgroundColor = $.NSColor.colorWithSRGBRedGreenBlueAlpha(0.043, 0.051, 0.094, 1);
	try {
		win.appearance = $.NSAppearance.appearanceNamed($('NSAppearanceNameDarkAqua'));
	} catch (e) {
		// before macOS 10.14 there is no dark appearance, the page is dark anyway
	}

	[0, 1, 2].forEach(function (kind) {
		var button = win.standardWindowButton(kind);
		if (!button.isNil()) {
			button.hidden = true;
		}
	});

	web = $.WKWebView.alloc.initWithFrameConfiguration($.NSMakeRect(0, 0, WIDTH, HEIGHT), $.WKWebViewConfiguration.alloc.init);
	try {
		web.setValueForKey($.NSNumber.numberWithBool(false), $('drawsBackground'));
	} catch (e) {
		// only avoids a white flash while the page loads
	}

	win.contentView = web;
	var url = $.NSURL.fileURLWithPath($(page));
	web.loadFileURLAllowingReadAccessToURL(url, url.URLByDeletingLastPathComponent);

	win.level = FLOATING;
	win.center;
	win.makeKeyAndOrderFront(null);
	app.activateIgnoringOtherApps(true);

	$.NSTimer.scheduledTimerWithTimeIntervalTargetSelectorUserInfoRepeats(0.25, $.FMProgressTicker.alloc.init, 'tick:', null, true);
	app.run;
}
FINEMINE_SCRIPT
}

main() {
	OS=$(uname -s)
	if [ "$OS" = Darwin ]; then
		HOME_DIR="$HOME/Library/Application Support/FINEMINE Starter"
	else
		HOME_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/finemine-starter"
	fi

	platform
	RUNTIME="$HOME_DIR/runtime/jre-$JAVA_VERSION-$ARCH"
	mkdir -p "$HOME_DIR" || fail "Не удалось создать папку $HOME_DIR"
	lock
	rm -f "$HOME_DIR/.progress"
	find_java || {
		install_java
		find_java || fail "Скачанная Java не запускается на этой системе. Скачайте .jar-версию лаунчера с finemine.su и установите Java вручную."
	}

	local jar="$HOME_DIR/FINEMINE.jar"
	if ! zip_complete "$jar"; then
		local size
		size=$(remote_size "$SITE/FINEMINE.jar")
		# A .part of the right size that is a complete zip was fully downloaded by a run that stopped right after;
		# anything else may be a different launcher version, so it is not continued but downloaded again
		if ! { [ "$size" -gt 0 ] && [ "$(file_size "$jar.part")" -eq "$size" ] && zip_complete "$jar.part"; }; then
			rm -f "$jar.part"
			say "скачиваю лаунчер..."
			progress download "Скачиваю лаунчер" "$jar.part" "$size"
			fetch "$SITE/FINEMINE.jar" "$jar.part" && zip_complete "$jar.part" || {
				rm -f "$jar.part"
				fail "Не удалось скачать лаунчер. Проверьте интернет и запустите снова."
			}
		fi
		mv -f "$jar.part" "$jar"
	fi

	local options=""
	if [ "$OS" = Darwin ]; then
		options="-Xdock:name=FINEMINE"
	else
		desktop_entry
		ffmpeg_libs
	fi
	# The launcher would otherwise pick the newest Java with JavaFX it finds in the system for its restart
	options="$options -Dlauncher.noJavaCheck=true"

	say "запускаю лаунчер"
	progress_done "Готово — запускаю лаунчер"
	unlock
	cd "$HOME_DIR" || exit 1
	if [ -t 2 ]; then
		exec "$JAVA" $options -jar "$jar" "$@"
	fi

	exec "$JAVA" $options -jar "$jar" "$@" >"$HOME_DIR/launcher.log" 2>&1
}

main "$@"
