#!/bin/bash
# zstock installer for macOS.
# Usage: curl -fsSL https://zstock.meluon.fun/install.sh | bash
#
# What it does: checks macOS 13+ on Apple silicon, downloads zstock.dmg, copies zstock.app into /Applications
# (quitting and replacing an older copy), removes the download quarantine flag so the first launch is not
# blocked (zstock is not notarized by Apple), then opens zstock.
# Your data in ~/Library/Application Support/com.zstock.app is untouched.
set -euo pipefail

APP_NAME="zstock.app"
INSTALL_DIR="/Applications"
TARGET="$INSTALL_DIR/$APP_NAME"
URL="https://zstock.meluon.fun/download/zstock.dmg"

if [[ "${LANG:-}${LC_ALL:-}" == *zh* ]]; then
  T_OS="zstock 只支持 macOS。"
  T_VER="zstock 需要 macOS 13 或更新版本，当前是"
  T_CPU="zstock 目前只支持 Apple 芯片（M 系列）的 Mac。"
  T_DL="正在下载 zstock..."
  T_DL_FAIL="下载失败，请检查网络后重试。"
  T_QUIT="正在退出正在运行的 zstock..."
  T_COPY="正在安装到 $INSTALL_DIR ..."
  T_PERM="没有写入 $INSTALL_DIR 的权限，改用 sudo（可能需要输入开机密码）..."
  T_DONE="安装完成，正在打开 zstock。第一次启动需要半分钟左右准备本地数据库。"
else
  T_OS="zstock runs on macOS only."
  T_VER="zstock needs macOS 13 or later; this Mac has"
  T_CPU="zstock currently supports Apple silicon Macs only."
  T_DL="Downloading zstock..."
  T_DL_FAIL="Download failed. Check your connection and try again."
  T_QUIT="Quitting the running zstock..."
  T_COPY="Installing to $INSTALL_DIR ..."
  T_PERM="No write access to $INSTALL_DIR; using sudo (you may be asked for your password)..."
  T_DONE="Done. Opening zstock; the first launch takes about half a minute to set up its local database."
fi

[[ "$(uname)" == "Darwin" ]] || { echo "$T_OS" >&2; exit 1; }
MAJOR=$(sw_vers -productVersion | cut -d. -f1)
(( MAJOR >= 13 )) || { echo "$T_VER $(sw_vers -productVersion)." >&2; exit 1; }
[[ "$(uname -m)" == "arm64" ]] || { echo "$T_CPU" >&2; exit 1; }

TMP="$(mktemp -d)"
MNT=""
cleanup() { [[ -n "$MNT" ]] && hdiutil detach "$MNT" -quiet -force >/dev/null 2>&1 || true; rm -rf "$TMP"; }
trap cleanup EXIT

echo "$T_DL"
curl -fL --progress-bar "$URL" -o "$TMP/zstock.dmg" || { echo "$T_DL_FAIL" >&2; exit 1; }
MNT="$TMP/mnt"
mkdir -p "$MNT"
hdiutil attach "$TMP/zstock.dmg" -nobrowse -readonly -quiet -mountpoint "$MNT" || { echo "$T_DL_FAIL" >&2; MNT=""; exit 1; }
[[ -d "$MNT/$APP_NAME" ]] || { echo "$T_DL_FAIL" >&2; exit 1; }

if pgrep -x zstock >/dev/null 2>&1; then
  echo "$T_QUIT"
  osascript -e 'tell application id "com.zstock.app" to quit' >/dev/null 2>&1 || pkill -x zstock || true
  sleep 2
fi

echo "$T_COPY"
SUDO=""
if [[ ! -w "$INSTALL_DIR" ]] || { [[ -e "$TARGET" ]] && [[ ! -w "$TARGET" ]]; }; then
  echo "$T_PERM"
  SUDO="sudo"
fi
$SUDO rm -rf "$TARGET"
$SUDO ditto "$MNT/$APP_NAME" "$TARGET"
$SUDO xattr -dr com.apple.quarantine "$TARGET" 2>/dev/null || true

echo "$T_DONE"
open "$TARGET" 2>/dev/null || true
