#!/usr/bin/env bash
# build-ios-clean.sh — iOS clean rebuild ohne Festplatten-bloat
#
# Cleart vor jedem Build:
#   - Rebreak DerivedData (NICHT alle Projects, nur Rebreak-*)
#   - ios/build/ (Xcode workspace build output)
#
# Optional via env:
#   CLEAN_PODS=1   → auch ios/Pods nukern + pod install (langsamer, ~3min extra)
#   SKIP_BUILD=1   → nur cleanup, kein expo run:ios
#
# Usage:
#   ./scripts/build-ios-clean.sh                     # cleanup + simulator-build
#   ./scripts/build-ios-clean.sh --device            # cleanup + device-build
#   CLEAN_PODS=1 ./scripts/build-ios-clean.sh        # full reset
#   SKIP_BUILD=1 ./scripts/build-ios-clean.sh        # nur disk freigeben

set -euo pipefail

cd "$(dirname "$0")/.."

echo "==================================="
echo "  iOS Clean-Build"
echo "==================================="

free_before=$(df -h / | tail -1 | awk '{print $4}')
echo "Free disk (before): $free_before"
echo ""

# 1. Sicherheits-check: läuft gerade ein Xcode/expo-build?
if pgrep -f "xcodebuild|expo run:ios" >/dev/null 2>&1; then
  echo "WARNUNG: xcodebuild oder expo run:ios läuft gerade."
  echo "  Cleanup würde laufenden Build kaputt machen. Abbruch."
  exit 1
fi

# 2. Rebreak DerivedData nukern (gezielt, nicht alle Projects)
DD_DIR="$HOME/Library/Developer/Xcode/DerivedData"
REBREAK_DDS=$(find "$DD_DIR" -maxdepth 1 -name "Rebreak-*" -type d 2>/dev/null || true)
if [ -n "$REBREAK_DDS" ]; then
  echo "==> Removing Rebreak DerivedData:"
  echo "$REBREAK_DDS" | sed 's/^/    /'
  echo "$REBREAK_DDS" | xargs rm -rf
else
  echo "==> No Rebreak DerivedData found (already clean)"
fi

# 3. ios/build/ (workspace build output, falls vorhanden)
if [ -d "ios/build" ]; then
  size=$(du -sh ios/build 2>/dev/null | awk '{print $1}')
  echo "==> Removing ios/build/ ($size)"
  rm -rf ios/build
fi

# 4. Optional: Pods komplett zurücksetzen
if [ "${CLEAN_PODS:-0}" = "1" ]; then
  if [ -d "ios/Pods" ]; then
    size=$(du -sh ios/Pods 2>/dev/null | awk '{print $1}')
    echo "==> CLEAN_PODS=1 → Removing ios/Pods/ ($size)"
    rm -rf ios/Pods ios/Podfile.lock
  fi
  echo "==> Running pod install"
  (cd ios && pod install)
fi

free_after=$(df -h / | tail -1 | awk '{print $4}')
echo ""
echo "Free disk (after):  $free_after"
echo ""

# 5. Build (außer SKIP_BUILD=1)
if [ "${SKIP_BUILD:-0}" = "1" ]; then
  echo "SKIP_BUILD=1 → cleanup-only, kein expo run:ios"
  exit 0
fi

echo "==> Starting expo run:ios $*"
exec npx expo run:ios "$@"
