#!/bin/bash
# Cài / cập nhật HTSLive trên Mac bằng MỘT lệnh Terminal (11-10-2026):
#
#   curl -fsSL https://huutichsop.com/tai-ve/cai-mac.sh | bash
#
# Vì sao: bản Mac chưa ký với Apple. Tải .dmg bằng trình duyệt thì macOS gắn cờ
# "cách ly" (com.apple.quarantine) và Gatekeeper đòi chuyển app vào Thùng rác.
# Tải bằng curl thì không có cờ đó — app mở được ngay. Dữ liệu (video, luật,
# cài đặt) ở ~/Library/Application Support/HuuTichSop Live, không bị đụng.
set -e
GOC="https://huutichsop.com/tai-ve"
echo ""
echo "== Cài HTSLive cho Mac =="

ZIP=$(curl -fsSL "$GOC/latest-mac.yml" | awk '/url:/ && /\.zip/ {print $NF; exit}')
BAN=$(curl -fsSL "$GOC/latest-mac.yml" | awk '/^version:/ {print $2; exit}')
if [ -z "$ZIP" ]; then echo "Không đọc được bản cài trên máy chủ. Thử lại sau."; exit 1; fi
echo "Bản: $BAN"

DICH="/Applications"
if [ ! -w "$DICH" ]; then DICH="$HOME/Applications"; mkdir -p "$DICH"; fi

TAM=$(mktemp -d)
trap 'rm -rf "$TAM"' EXIT
echo "Đang tải (khoảng 250 MB)..."
curl -fL --progress-bar "$GOC/$ZIP" -o "$TAM/htslive.zip"

# App tự cập nhật bằng chính script này (electron/updater.js) — mà luật số một
# là KHÔNG BAO GIỜ cắt buổi live: đang live thì chờ tới khi buổi live xong.
while curl -fs -m 3 http://127.0.0.1:4000/api/connection 2>/dev/null | grep -qE '"status":"(connected|reconnecting)"'; do
  echo "HTSLive đang live — chờ buổi live kết thúc rồi mới cài..."
  sleep 30
done

# Đang mở thì tắt trước khi thay.
osascript -e 'tell application "HTSLive" to quit' >/dev/null 2>&1 || true
sleep 1
pkill -x HTSLive >/dev/null 2>&1 || true

echo "Đang cài vào $DICH ..."
rm -rf "$DICH/HTSLive.app"
ditto -x -k "$TAM/htslive.zip" "$DICH/"
xattr -dr com.apple.quarantine "$DICH/HTSLive.app" >/dev/null 2>&1 || true

echo "Xong! Đang mở HTSLive..."
open "$DICH/HTSLive.app"
echo ""
