#!/bin/bash
set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT="$PROJECT_DIR/MLaunchy.xcodeproj"
SCHEME="MLaunchy"
APP_NAME="MLaunchy.app"
INSTALL_DIR="/Applications"
BUNDLE_ID="ch.amzu.MLaunchy"
ARCHIVE_DIR="$PROJECT_DIR/build"
ARCHIVE_PATH="$ARCHIVE_DIR/MLaunchy.xcarchive"

# --- Increment build number ---
PBXPROJ="$PROJECT/project.pbxproj"
APPCONFIG="$PROJECT_DIR/MLaunchy/appconfig.json"
# Find the highest CURRENT_PROJECT_VERSION to determine the current build
CURRENT_BUILD=$(grep 'CURRENT_PROJECT_VERSION' "$PBXPROJ" | grep -v shellScript | sed 's/[^0-9]//g' | sort -rn | head -1)
NEW_BUILD=$((CURRENT_BUILD + 1))
echo "Build number: $CURRENT_BUILD -> $NEW_BUILD"

# Update all CURRENT_PROJECT_VERSION entries (app Debug+Release and test Debug+Release)
sed -i '' "s/CURRENT_PROJECT_VERSION = [0-9]*/CURRENT_PROJECT_VERSION = $NEW_BUILD/g" "$PBXPROJ"

# Sync appconfig.json "build" so AppConfig.build matches pbxproj.
sed -i '' -E "s/\"build\": \"[0-9]+\"/\"build\": \"$NEW_BUILD\"/" "$APPCONFIG"

# --- Write build date ---
BUILD_DATE=$(date '+%Y-%m-%d %H:%M')
cat > "$PROJECT_DIR/MLaunchy/BuildInfo.swift" << SWIFT
enum BuildInfo {
    static let date = "$BUILD_DATE"
}
SWIFT
echo "Build date: $BUILD_DATE"

# --- Run tests ---
# Unit suite only — UI tests need accessibility/hotkey grants the build host
# may not have, and cannot be driven non-interactively here.
echo "Running unit tests..."
if ! xcodebuild test \
    -project "$PROJECT" \
    -scheme "$SCHEME" \
    -configuration Debug \
    -only-testing:MLaunchyTests \
    -quiet 2>&1; then
    echo "Error: Tests failed. Aborting build."
    exit 1
fi
echo "Tests passed."

# --- Kill all running instances ---
if pgrep -f "$BUNDLE_ID" >/dev/null 2>&1 || pgrep -x MLaunchy >/dev/null 2>&1; then
    echo "Stopping all running MLaunchy instances..."
    pkill -f "$BUNDLE_ID" 2>/dev/null || true
    killall MLaunchy 2>/dev/null || true
    sleep 1
    # Force kill any remaining
    pkill -9 -f "$BUNDLE_ID" 2>/dev/null || true
    killall -9 MLaunchy 2>/dev/null || true
fi

# --- Build (Release archive) ---
echo "Building MLaunchy (Release)..."
mkdir -p "$ARCHIVE_DIR"
xcodebuild archive \
    -project "$PROJECT" \
    -scheme "$SCHEME" \
    -configuration Release \
    -archivePath "$ARCHIVE_PATH" \
    -quiet

# --- Install ---
BUILT_APP="$ARCHIVE_PATH/Products/Applications/$APP_NAME"
if [ ! -d "$BUILT_APP" ]; then
    echo "Error: Archive succeeded but $APP_NAME not found at expected path."
    exit 1
fi

echo "Installing to $INSTALL_DIR..."
rm -rf "$INSTALL_DIR/$APP_NAME"
cp -R "$BUILT_APP" "$INSTALL_DIR/$APP_NAME"

# --- Launch ---
echo "Launching MLaunchy..."
open "$INSTALL_DIR/$APP_NAME"

echo "Done. MLaunchy build $NEW_BUILD installed and running."
