#!/bin/bash
# 星櫻戰境 iPhone 版：在 Mac 上準備建置環境，並先編譯一次（不簽名）。
# 用法（在 Mac 的「終端機」貼上這一行）：
#   curl -fsSL http://192.168.0.107:8088/mac-setup.sh | bash          （在家，同一個 Wi-Fi）
#   curl -fsSL https://seem-9800x3d.taila4662e.ts.net/mac-setup.sh | bash   （在外面，任何網路）
# 離線用法（Mac 連不到 Windows 時）：把 hoshi-mac.zip 拉到 Mac、解壓縮，然後
#   bash ~/Downloads/hoshi-mac/mac-setup.sh
#   （資料夾裡的 hoshi-ios-xcode.zip、mac-install.sh 會直接拿來用，不需要網路）
# 這個腳本不會要任何密碼、不會安裝 Apple 以外的東西，所有檔案放在 ~/hoshi。
# 注意：這個腳本是在 Windows 上寫的，還沒有在 Mac 上實際跑過。卡住的話把畫面上的訊息回報給 Windows 那邊。
set -u
BASES="http://192.168.0.107:8088 http://100.123.27.23:8088 https://seem-9800x3d.taila4662e.ts.net"
WORK="$HOME/hoshi"
# 這個腳本所在的資料夾（離線包解壓縮出來的地方）；用 curl | bash 執行時是目前所在的資料夾
SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd)"
LOCAL_ZIP=""
for f in "$SELF_DIR/hoshi-ios-xcode.zip" "$HOME/Downloads/hoshi-mac/hoshi-ios-xcode.zip" "$HOME/Desktop/hoshi-mac/hoshi-ios-xcode.zip"; do
  if [ -f "$f" ] && [ "$f" != "$WORK/hoshi-ios-xcode.zip" ]; then LOCAL_ZIP="$f"; break; fi
done
mkdir -p "$WORK"; cd "$WORK" || exit 1

echo "== 1. 這台 Mac 的環境 =="
sw_vers 2>/dev/null
echo "晶片：$(uname -m)"
df -h "$HOME" | tail -1 | awk '{print "家目錄可用空間：" $4}'
if ! xcodebuild -version >/dev/null 2>&1; then
  echo
  echo "!! 還沒裝 Xcode（或還沒開過一次）。"
  echo "   請打開 App Store，搜尋 Xcode 安裝（很大，要一段時間）。裝好後打開一次、同意條款，再重新執行這個腳本。"
  exit 2
fi
xcodebuild -version
if ! xcodebuild -showsdks 2>/dev/null | grep -q iphoneos; then
  echo
  echo "!! Xcode 裡沒有 iOS 的元件。請執行：xcodebuild -downloadPlatform iOS   （或打開 Xcode → Settings → Components 下載 iOS）"
  exit 3
fi

echo
echo "== 2. 取得專案 =="
URL=""
if [ -n "$LOCAL_ZIP" ]; then
  # 離線包：直接用旁邊那份
  WANT=$(stat -f%z "$LOCAL_ZIP")
  HAVE=0; [ -f hoshi-ios-xcode.zip ] && HAVE=$(stat -f%z hoshi-ios-xcode.zip)
  if [ "$HAVE" != "$WANT" ]; then
    echo "使用離線包裡的專案：$LOCAL_ZIP（$WANT 位元組）"
    cp "$LOCAL_ZIP" hoshi-ios-xcode.zip || { echo "!! 複製失敗"; exit 5; }
    rm -rf hoshi-ios
  else
    echo "已經是這一版，不重新複製。"
  fi
else
  for b in $BASES; do
    if curl -fsI -m 8 "$b/hoshi-ios-xcode.zip" >/dev/null 2>&1; then URL="$b/hoshi-ios-xcode.zip"; break; fi
  done
  if [ -z "$URL" ]; then
    echo "!! 連不到 Windows 電腦，旁邊也沒有離線包。"
    echo "   在家：跟 Windows 電腦連同一個 Wi-Fi 再跑一次。在外面：把 hoshi-mac.zip 拉到 Mac、解壓縮後執行 bash ~/Downloads/hoshi-mac/mac-setup.sh"
    exit 4
  fi
  WANT=$(curl -fsI -m 10 "$URL" | tr -d '\r' | awk 'tolower($1)=="content-length:" {print $2}')
  HAVE=0; [ -f hoshi-ios-xcode.zip ] && HAVE=$(stat -f%z hoshi-ios-xcode.zip)
  if [ "$HAVE" != "$WANT" ]; then
    echo "從 $URL 下載（$WANT 位元組）…"
    curl -fL -o hoshi-ios-xcode.zip "$URL" || { echo "!! 下載失敗"; exit 5; }
    rm -rf hoshi-ios
  else
    echo "已經有最新的壓縮檔，不重新下載。"
  fi
fi
if [ ! -d hoshi-ios/Unity-iPhone.xcodeproj ]; then
  echo "解壓縮…"
  ditto -x -k hoshi-ios-xcode.zip . || { echo "!! 解壓縮失敗"; exit 6; }
fi

echo
echo "== 3. 先不簽名編譯一次（第一次約 10～30 分鐘，請不要關掉視窗） =="
cd "$WORK/hoshi-ios" || exit 7
# 只看 -showsdks 不夠：新版 Xcode 就算有 SDK，沒裝「iOS 平台元件」也編不了（會說 iOS xx.x is not installed）。
# 所以直接問這個專案能不能編給「Any iOS Device」。（Mac 端實測回報，2026-11-26）
DEST=$(xcodebuild -project Unity-iPhone.xcodeproj -scheme Unity-iPhone -showdestinations 2>&1)
if ! echo "$DEST" | grep "Any iOS Device" | grep -qv "error:"; then
  echo "!! Xcode 還沒裝好 iOS 平台元件。請執行（約 10GB，要等一陣子）："
  echo "     xcodebuild -downloadPlatform iOS"
  echo "   裝完之後再重新執行這個腳本。"
  echo "$DEST" | grep -i "not installed" | head -3
  exit 3
fi
xcodebuild -project Unity-iPhone.xcodeproj -scheme Unity-iPhone -configuration Release -sdk iphoneos \
  -destination 'generic/platform=iOS' -derivedDataPath "$WORK/DerivedData" \
  CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO build > "$WORK/build.log" 2>&1
RC=$?
tail -3 "$WORK/build.log"
if [ $RC -ne 0 ]; then
  echo
  echo "!! 編譯失敗。前幾個錯誤："
  grep -n "error:" "$WORK/build.log" | head -30
  echo "完整記錄在 $WORK/build.log 。請把上面的錯誤回報給 Windows 那邊。"
  exit 8
fi

# 備用：把編好的 App 包成一個還沒簽名的安裝檔。萬一這台 Mac 的 Xcode 太舊、裝不進新版 iOS 的手機，
# 可以改用 AltStore／Sideloadly 這類工具（用自己的 Apple ID 簽名）把這個檔案裝進去。
APP=$(find "$WORK/DerivedData/Build/Products" -maxdepth 2 -name "*.app" -path "*iphoneos*" | head -1)
if [ -n "$APP" ]; then
  rm -rf "$WORK/ipa"; mkdir -p "$WORK/ipa/Payload"; cp -R "$APP" "$WORK/ipa/Payload/"
  (cd "$WORK/ipa" && zip -qry ../hoshi-unsigned.ipa Payload) && echo "備用安裝檔：$WORK/hoshi-unsigned.ipa"
fi

echo
echo "== 4. 準備明天的安裝指令 =="
if [ -f "$SELF_DIR/mac-install.sh" ]; then cp "$SELF_DIR/mac-install.sh" "$WORK/install.sh"; else curl -fsSL -o "$WORK/install.sh" "${URL%/*}/mac-install.sh"; fi
chmod +x "$WORK/install.sh" 2>/dev/null
echo
echo "編譯成功。還剩下只有你本人能做的事："
echo "  1. 打開 Xcode → Settings（設定）→ Accounts → 按 + → 加入你的 Apple ID（免費帳號就可以）。"
echo "  2. 明天 iPhone 接上線：手機按「信任這部電腦」；設定 → 隱私權與安全性 → 開發者模式 打開（會重開機）。"
echo "  3. 然後在終端機執行：  bash ~/hoshi/install.sh"
