#!/bin/sh

set -eu

RELEASE_PACKAGE_URL='https://api.nrd.nie.163.com/api/v1/release/dl/8?channel=gwqd'

usage() {
	cat <<'EOF'
Usage: sudo sh install.sh
       install.sh [--package-url <https-url>]

Installer for Linux Standard on Ubuntu 18.04 or newer.
The release download endpoint must select the current official website version.
--package-url overrides the endpoint for local verification only.
Installation runs without confirmation and may stop existing clients.
No checksum or publisher signature verification is performed.
The UU GUI and device login are not started automatically.
UU 远程安装成功后，Wayland 会话可选择安装第三方 GNOME 锁屏远程桌面扩展；X11 静默跳过。
默认不安装；无交互终端或无对应 GNOME 桌面会话时自动跳过。
EOF
}

fail() {
	printf '[ERROR] stage=%s reason=%s\n' "$stage" "$1" >&2
	exit 1
}

install_optional_extension() (
	if ! (exec 3<> /dev/tty) 2>/dev/null; then
		printf '[扩展] 无交互终端，跳过可选 GNOME 扩展。\n'
		return 0
	fi
	exec 3<> /dev/tty
	desktop_uid="${SUDO_UID:-}"
	case "$desktop_uid" in
		''|*[!0-9]*|0)
		printf '[扩展] 请从普通 GNOME 桌面用户的终端使用 sudo 运行；本次跳过。\n'
		return 0
		;;
	esac
	if ! command -v loginctl >/dev/null; then
		printf '[扩展] 缺少工具 loginctl，跳过；UU 远程安装不受影响。\n'
		return 0
	fi
	session_id="$(loginctl show-user "$desktop_uid" --property=Display --value)" || return 1
	if [ -z "$session_id" ]; then
		printf '[扩展] 未找到该用户的桌面会话，跳过。\n'
		return 0
	fi
	session_info="$(loginctl show-session "$session_id" --property=User --property=Active --property=Type --property=Class --property=Remote)" || return 1
	session_uid=''; session_active=''; session_type=''; session_class=''; session_remote=''
	while IFS='=' read -r property value; do
		case "$property" in
			User) session_uid="$value" ;; Active) session_active="$value" ;;
			Type) session_type="$value" ;; Class) session_class="$value" ;; Remote) session_remote="$value" ;;
		esac
	done <<EOF
$session_info
EOF
	if [ "$session_uid" != "$desktop_uid" ] || [ "$session_active" != yes ] ||
	   [ "$session_class" != user ] || [ "$session_remote" != no ] ||
	   { [ "$session_type" != x11 ] && [ "$session_type" != wayland ]; }; then
		printf '[扩展] 无匹配的活动本地桌面会话，跳过。\n'
		return 0
	fi
	if [ "$session_type" = x11 ]; then return 0; fi
	for tool in getent stat runuser gdbus gnome-extensions timeout; do
		if ! command -v "$tool" >/dev/null; then
			printf '[扩展] 缺少工具 %s，跳过；UU 远程安装不受影响。\n' "$tool"
			return 0
		fi
	done
	account="$(getent passwd "$desktop_uid")" || return 1
	IFS=: read -r desktop_user account_password account_uid account_gid account_name desktop_home account_shell <<EOF
$account
EOF
	if [ -z "$desktop_user" ] || [ "$account_uid" != "$desktop_uid" ] || [ "${desktop_home#/}" = "$desktop_home" ]; then
		printf '[扩展] 无法确认桌面用户身份，跳过。\n'
		return 0
	fi
	bus_path="/run/user/$desktop_uid/bus"
	bus_identity="$(stat -c '%u:%F' -- "$bus_path" 2>/dev/null)" || return 1
	if [ "$bus_identity" != "$desktop_uid:socket" ]; then
		printf '[扩展] 桌面会话总线身份不匹配，跳过。\n'
		return 0
	fi
	extension_uuid='allowlockedremotedesktop@kamens.us'
	desktop_call() {
		runuser -u "$desktop_user" -- env -i HOME="$desktop_home" USER="$desktop_user" LOGNAME="$desktop_user" \
			PATH=/usr/sbin:/usr/bin:/sbin:/bin LC_ALL=C XDG_RUNTIME_DIR="/run/user/$desktop_uid" \
			DBUS_SESSION_BUS_ADDRESS="unix:path=$bus_path" "$@"
	}
	extension_state() (
		info="$(desktop_call timeout 15 gnome-extensions info "$extension_uuid" 2>/dev/null)" || return 1
		state="$(printf '%s\n' "$info" | sed -n 's/^[[:space:]]*State:[[:space:]][[:space:]]*\(.\{1,\}\)$/\1/p')" || return 1
		[ -n "$state" ] || return 1
		printf '%s\n' "$state"
	)
	shell_reply="$(desktop_call gdbus call --session --timeout 10 --dest org.gnome.Shell.Extensions \
		--object-path /org/gnome/Shell/Extensions --method org.freedesktop.DBus.Properties.Get \
		org.gnome.Shell.Extensions ShellVersion 2>/dev/null)" || {
		printf '[扩展] 未找到可用的 GNOME 扩展服务，跳过。\n'; return 0;
	}
	shell_version="$(printf '%s\n' "$shell_reply" | sed -n "s/.*'\([0-9][0-9]*\.[0-9][0-9]*\)\(\.[0-9][0-9]*\)*'.*/\1/p")" || return 1
	if [ -z "$shell_version" ]; then
		printf '[扩展] 无法确认 GNOME Shell 版本，跳过。\n'; return 0
	fi
	if ! dpkg --compare-versions "$shell_version" ge 3.38; then
		printf '[扩展] GNOME Shell %s 不满足该扩展的最低版本要求，跳过。\n' "$shell_version"; return 0
	fi
	extension_list="$(desktop_call timeout 15 gnome-extensions list 2>/dev/null)" || return 1
	extension_installed=false
	if printf '%s\n' "$extension_list" | grep -F -x "$extension_uuid" >/dev/null; then
		extension_installed=true
		current_state="$(extension_state)" || return 1
		if [ "$current_state" = ACTIVE ] || [ "$current_state" = ENABLED ]; then
			printf '[扩展] 已安装并启用，无需重复安装。\n'; return 0
		fi
	fi
	enabled_reply="$(desktop_call gdbus call --session --timeout 10 --dest org.gnome.Shell.Extensions \
		--object-path /org/gnome/Shell/Extensions --method org.freedesktop.DBus.Properties.Get \
		org.gnome.Shell.Extensions UserExtensionsEnabled 2>/dev/null)" || return 1
	if [ "$enabled_reply" != '(<true>,)' ]; then
		printf '[扩展] GNOME 全局用户扩展开关已关闭或状态无法确认；不会自动更改，跳过。\n'; return 0
	fi
	printf '\n可选扩展：Allow Locked Remote Desktop\n安装用户：%s，GNOME Shell：%s\n' "$desktop_user" "$shell_version"
	printf '%s\n' '来源：GNOME 官方扩展平台，第三方维护，非 UU 远程或 GNOME 官方内置组件。' \
		'官网：https://extensions.gnome.org/extension/4338/allow-locked-remote-desktop/' \
		'用途：允许 GNOME 在锁屏状态下继续远程桌面连接。' \
		'风险：会改变默认锁屏远程访问保护，锁屏时仍可能被远程访问；扩展可能影响桌面稳定性，系统升级后可能不兼容。' \
		'请仅在信任远程访问人员、并符合设备安全策略时安装。安装时可能还需在 GNOME 桌面确认。'
	printf '是否安装并启用该扩展？[y/N] '
	if ! IFS= read -r answer <&3; then answer=''; fi
	case "$answer" in y|Y|yes|YES) ;; *) printf '[扩展] 已跳过。\n'; return 0 ;; esac
	if ! "$extension_installed"; then
		printf '[扩展] 请在 GNOME 桌面弹窗中确认安装，最多等待 180 秒；可选择取消。\n'
		install_reply="$(desktop_call gdbus call --session --timeout 180 --dest org.gnome.Shell \
			--object-path /org/gnome/Shell --method org.gnome.Shell.Extensions.InstallRemoteExtension \
			"$extension_uuid" 2>&1)" || {
			printf '[扩展] 安装请求失败或超时；UU 远程已安装成功。\n%s\n' "$install_reply"; return 0;
		}
		if [ "$install_reply" = "('cancelled',)" ]; then
			printf '[扩展] 已取消安装；UU 远程安装不受影响。\n'; return 0
		fi
	fi
	current_state="$(extension_state)" || { printf '[扩展] 无法确认安装结果；请在 GNOME 扩展管理器检查。\n'; return 0; }
	case "$current_state" in
		ACTIVE|ENABLED) ;;
		INACTIVE|DISABLED|INITIALIZED)
			if ! desktop_call timeout 15 gnome-extensions enable "$extension_uuid"; then
				printf '[扩展] 启用失败；UU 远程已安装成功。\n'; return 0
			fi
			current_state="$(extension_state)" || return 1 ;;
		*) printf '[扩展] 扩展存在错误或版本不兼容，未强制启用。\n'; return 0 ;;
	esac
	if [ "$current_state" = ACTIVE ] || [ "$current_state" = ENABLED ]; then
		printf '[扩展] 已安装并启用。锁屏远控效果仍需实际验证。\n'
	else
		printf '[扩展] 未确认启用成功；请在 GNOME 扩展管理器检查。\n'
	fi
)

main() (
	export PATH=/usr/sbin:/usr/bin:/sbin:/bin
	export LC_ALL=C
	umask 077
	stage=arguments
	package_url="$RELEASE_PACKAGE_URL"
	expected_version=''
	temporary_dir=''
	trap 'if [ -n "$temporary_dir" ]; then rm -rf -- "$temporary_dir"; fi' 0
	trap 'exit 130' INT
	trap 'exit 143' TERM
	while [ "$#" -gt 0 ]; do
		case "$1" in
			--package-url)
				[ "$#" -ge 2 ] || fail missing-argument
				package_url="$2"
				shift 2
				;;
			--help|-h) usage; exit 0 ;;
			*) fail unknown-argument ;;
		esac
	done
	[ -n "$package_url" ] || fail release-download-url-not-configured
	case "$package_url" in
		*[[:space:][:cntrl:]]*|*'#'*|*'\'*) fail invalid-https-url ;;
	esac
	printf '%s\n' "$package_url" | grep -E '^https://[A-Za-z0-9][A-Za-z0-9.-]*(:[0-9]+)?/[^[:space:]]+$' >/dev/null || fail invalid-https-url
	stage=preflight
	[ "$(uname -s)" = Linux ] || fail unsupported-kernel
	[ "$(id -u)" = 0 ] || fail root-required
	for tool in grep sed cat curl dpkg dpkg-deb dpkg-query apt-get mktemp rm chmod systemctl; do
		command -v "$tool" >/dev/null || fail "missing-tool-$tool"
	done
	host_architecture="$(dpkg --print-architecture)" || fail architecture-unavailable
	[ -n "$host_architecture" ] || fail architecture-unavailable
	os_release="$(cat /etc/os-release)" || fail os-release-unavailable
	printf '%s\n' "$os_release" | grep -E '^ID="?ubuntu"?$' >/dev/null || fail unsupported-distribution
	os_version="$(printf '%s\n' "$os_release" | sed -n 's/^VERSION_ID="\{0,1\}\([0-9][0-9]*\.[0-9][0-9]*\)"\{0,1\}$/\1/p')" || fail unsupported-os-version
	[ -n "$os_version" ] || fail unsupported-os-version
	dpkg --compare-versions "$os_version" ge 18.04 || fail unsupported-os-version
	systemctl show --property=Version --value >/dev/null || fail systemd-unavailable

	tab="$(printf '\t')"
	installed_status=''
	installed_version=''
	if installed_info="$(dpkg-query -W -f='${Status}\t${Version}' uuyc 2>/dev/null)"; then
		installed_status="${installed_info%%"$tab"*}"
		installed_version="${installed_info#*"$tab"}"
	fi
	printf '[INFO] product=Standard arch=%s installed=%s\n' "$host_architecture" "${installed_version:-none}"
	stage=download
	temporary_dir="$(mktemp -d /tmp/uuyc-install.XXXXXXXXXX)" || fail temporary-directory-failed
	package_file="$temporary_dir/uuyc.deb"
	curl --fail --show-error --location --proto '=https' --proto-redir '=https' \
		--connect-timeout 15 --max-time 600 --retry 2 \
		--output "$package_file" -- "$package_url" || fail download-failed
	stage=verify
	dpkg-deb --info "$package_file" >/dev/null 2>&1 || fail invalid-deb
	[ "$(dpkg-deb -f "$package_file" Package)" = uuyc ] || fail package-name-mismatch
	[ "$(dpkg-deb -f "$package_file" Architecture)" = "$host_architecture" ] || fail package-architecture-mismatch
	package_version="$(dpkg-deb -f "$package_file" Version)" || fail package-version-unavailable
	case "$package_version" in *[!0-9.-]*) fail invalid-package-version ;; esac
	printf '%s\n' "$package_version" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+-[0-9]+$' >/dev/null || fail invalid-package-version
	expected_version="$package_version"
	if [ "$installed_status" = 'install ok installed' ] && \
	   dpkg --compare-versions "$installed_version" gt "$expected_version"; then
		printf '[错误] 安装已停止：下载版本（%s）低于本机已安装版本（%s），不允许降级。\n' "$expected_version" "$installed_version" >&2
		fail downgrade-refused
	fi
	printf '[INFO] target-version=%s\n' "$expected_version"
	if [ "$installed_status" != 'install ok installed' ] || [ "$installed_version" != "$expected_version" ]; then
		stage=install
		chmod 0755 "$temporary_dir"
		chmod 0644 "$package_file"
		DEBIAN_FRONTEND=noninteractive apt-get -y install "$package_file" || fail apt-install-failed
	else
		printf '[INFO] Same version already installed; checking installation without reinstalling.\n'
	fi

	stage=check
	installed_info="$(dpkg-query -W -f='${Status}\t${Version}' uuyc)" || fail package-query-failed
	[ "$installed_info" = "install ok installed${tab}${expected_version}" ] || fail installed-package-mismatch
	if ! systemctl is-enabled --quiet uuyc.socket || ! systemctl is-enabled --quiet uuyc.service || \
	   ! systemctl is-active --quiet uuyc.socket; then
		fail package-installed-control-socket-check-failed
	fi
	printf '[OK] package=uuyc version=%s control-socket=active\n' "$expected_version"
	printf '[INFO] Start uuyc from a normal desktop user. Device login/online status is not checked.\n'
	if ! install_optional_extension; then
		printf '[扩展] 可选步骤未完成；UU 远程已安装成功，不受影响。\n'
	fi
)

main "$@"
