#!/usr/bin/env bash
# Nyx installer — downloads and installs Nyx.app in /Applications
# Version: 0.7.3
# Docs:    https://getnyx.dev

set -euo pipefail

NYX_VERSION='0.7.3'
NYX_URL='https://dl.getnyx.dev/mac/0.7.3/Nyx-0.7.3-arm64.dmg?_v=77b5482c'
NYX_SHA256='77b5482caf8ec1169fbe377f62c59803baaf705b5502f9becc8378fd94273110'

# ─── Styling ─────────────────────────────────────────────────────────
if [ -t 1 ]; then
  BOLD=$'\033[1m'
  DIM=$'\033[2m'
  RED=$'\033[31m'
  GREEN=$'\033[32m'
  CYAN=$'\033[36m'
  RESET=$'\033[0m'
else
  BOLD=''; DIM=''; RED=''; GREEN=''; CYAN=''; RESET=''
fi

say()  { printf "%s\n" "$1"; }
step() { printf "\n${CYAN}${BOLD}▸ %s${RESET}\n" "$1"; }
ok()   { printf "  ${GREEN}✓${RESET} %s\n" "$1"; }
err()  { printf "  ${RED}✗ %s${RESET}\n" "$1" >&2; }

cleanup() {
  [ -n "${TMPDIR_NYX:-}" ] && [ -d "$TMPDIR_NYX" ] && rm -rf "$TMPDIR_NYX"
  [ -n "${MOUNT_POINT:-}" ] && [ -d "$MOUNT_POINT" ] && hdiutil detach "$MOUNT_POINT" -quiet 2>/dev/null || true
}
trap cleanup EXIT

# ─── Preflight ────────────────────────────────────────────────────────
if [ "$(uname)" != "Darwin" ]; then
  err "This installer is macOS only. You are on $(uname)."
  exit 1
fi

ARCH="$(uname -m)"
if [ "$ARCH" != "arm64" ]; then
  err "Nyx supports only Apple Silicon (arm64). Detected: $ARCH"
  exit 1
fi

printf "\n${BOLD}Nyx ${NYX_VERSION}${RESET} ${DIM}· macOS installer${RESET}\n"
printf "${DIM}Source: https://getnyx.dev${RESET}\n"

# ─── Quit running Nyx ────────────────────────────────────────────────
if pgrep -xq Nyx 2>/dev/null; then
  step "Quitting running Nyx"
  osascript -e 'quit app "Nyx"' 2>/dev/null || true
  sleep 1
  pkill -x Nyx 2>/dev/null || true
  ok "stopped"
fi

# ─── Download ────────────────────────────────────────────────────────
TMPDIR_NYX="$(mktemp -d -t nyx-install.XXXXXX)"
DMG_PATH="$TMPDIR_NYX/Nyx.dmg"

step "Downloading Nyx $NYX_VERSION"
say "  ${DIM}$NYX_URL${RESET}"
if ! curl --fail --location --progress-bar --output "$DMG_PATH" "$NYX_URL"; then
  err "download failed"
  exit 1
fi
ok "saved"

# ─── Verify checksum ─────────────────────────────────────────────────
if [ -n "$NYX_SHA256" ]; then
  step "Verifying checksum"
  ACTUAL="$(shasum -a 256 "$DMG_PATH" | awk '{print $1}')"
  if [ "$ACTUAL" != "$NYX_SHA256" ]; then
    err "SHA256 mismatch"
    say "  expected: $NYX_SHA256"
    say "  actual:   $ACTUAL"
    say "  ${DIM}Refusing to install tampered build.${RESET}"
    exit 1
  fi
  ok "sha256 matches"
else
  say "${DIM}  (checksum not provided for this release — skipped)${RESET}"
fi

# ─── Mount DMG ───────────────────────────────────────────────────────
step "Mounting DMG"
# hdiutil -plist отдаёт XML с system-entities, парсим через plutil (всегда есть на macOS).
# Не используем grep/awk по stdout — hdiutil output format разный в зависимости от
# того есть ли -quiet, язык системы и т.д.
MOUNT_PLIST="$TMPDIR_NYX/mount.plist"
if ! hdiutil attach -nobrowse -noautoopen -plist "$DMG_PATH" > "$MOUNT_PLIST" 2>&1; then
  err "hdiutil attach failed"
  cat "$MOUNT_PLIST" >&2
  exit 1
fi
# Пытаемся каждое entity по очереди — у одного из них будет mount-point.
MOUNT_POINT=""
for idx in 0 1 2 3 4 5; do
  MOUNT_POINT="$(plutil -extract "system-entities.$idx.mount-point" raw "$MOUNT_PLIST" 2>/dev/null || true)"
  if [ -n "$MOUNT_POINT" ] && [ -d "$MOUNT_POINT/Nyx.app" ]; then
    break
  fi
  MOUNT_POINT=""
done
if [ -z "$MOUNT_POINT" ]; then
  err "could not find Nyx.app inside DMG"
  say "  ${DIM}mount plist saved at $MOUNT_PLIST for debugging${RESET}"
  exit 1
fi
ok "mounted at $MOUNT_POINT"

# ─── Install ─────────────────────────────────────────────────────────
step "Installing to /Applications"
DEST="/Applications/Nyx.app"

if [ -d "$DEST" ]; then
  say "  ${DIM}removing previous install${RESET}"
  rm -rf "$DEST"
fi

# rsync лучше cp — корректно обрабатывает extended attributes + permissions
if ! rsync -a --delete "$MOUNT_POINT/Nyx.app/" "$DEST/"; then
  err "copy failed (permissions?)"
  say "  ${DIM}Hint: try running the installer with sudo if /Applications is locked.${RESET}"
  exit 1
fi
ok "copied"

# Страховка: убираем quarantine attribute (curl его не ставит, но бывают edge cases
# типа когда скрипт запускают через Safari pipe или браузер-based файл-менеджер).
xattr -dr com.apple.quarantine "$DEST" 2>/dev/null || true

# ─── Launch ──────────────────────────────────────────────────────────
step "Launching Nyx"
open "$DEST"
ok "Nyx is starting"

printf "\n${GREEN}${BOLD}Done.${RESET} Nyx ${NYX_VERSION} installed to ${DEST}\n"
printf "${DIM}Re-run this installer anytime to update.${RESET}\n\n"
