#!/bin/bash
# ZWord 一行安装 / one-line installer
# curl -fsSL https://zword.meluon.fun/install.sh | bash
set -euo pipefail

URL="https://zword.meluon.fun/download/ZWord.zip"
DEST="/Applications/ZWord.app"

case "${LANG:-${LC_ALL:-en}}" in zh*) ZH=1 ;; *) ZH=0 ;; esac
say() { if [ "$ZH" = 1 ]; then echo "$1"; else echo "$2"; fi; }

[ "$(uname)" = "Darwin" ] || { say "这个脚本只支持 macOS。" "This installer only supports macOS."; exit 1; }
MAJOR=$(sw_vers -productVersion | cut -d. -f1)
if [ "$MAJOR" -lt 14 ]; then
  say "ZWord 需要 macOS 14 或更高版本，你的是 $(sw_vers -productVersion)。" "ZWord needs macOS 14 or later (you have $(sw_vers -productVersion))."
  exit 1
fi

TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
say "正在下载 ZWord…" "Downloading ZWord…"
curl -fL --progress-bar "$URL" -o "$TMP/ZWord.zip" || { say "下载失败，请检查网络后重试。" "Download failed. Check your connection and try again."; exit 1; }
ditto -x -k "$TMP/ZWord.zip" "$TMP/x"
[ -d "$TMP/x/ZWord.app" ] || { say "安装包不完整，请重试。" "The download looks broken. Please try again."; exit 1; }

if pgrep -x ZWord >/dev/null 2>&1; then
  say "正在关闭正在运行的 ZWord…" "Quitting the running ZWord…"
  osascript -e 'quit app "ZWord"' >/dev/null 2>&1 || true
  sleep 1; pkill -x ZWord >/dev/null 2>&1 || true
fi

say "正在安装到“应用程序”…" "Installing to /Applications…"
if [ -w /Applications ]; then
  rm -rf "$DEST"; ditto "$TMP/x/ZWord.app" "$DEST"
else
  sudo rm -rf "$DEST"; sudo ditto "$TMP/x/ZWord.app" "$DEST"
fi
xattr -dr com.apple.quarantine "$DEST" 2>/dev/null || sudo xattr -dr com.apple.quarantine "$DEST" 2>/dev/null || true

say "安装完成，正在打开 ZWord。第一次打开请按引导允许“辅助功能”和“通知”。" "Done. Opening ZWord — allow Accessibility and Notifications when asked."
open "$DEST"
