#!/bin/bash
# ==============================================================================
# MECTOR HUD — 1-Click Launch & Gatekeeper Fix for Friends
# ==============================================================================

clear
echo "========================================================================"
echo "          🛡️   MECTOR HUD — 1-CLICK LAUNCH & GATEKEEPER FIX"
echo "========================================================================"
echo ""

DIR="$(cd "$(dirname "$0")" && pwd)"

# 1. Determine where Mector HUD.app is located
APP_TARGET=""
if [ -d "/Applications/Mector HUD.app" ]; then
    APP_TARGET="/Applications/Mector HUD.app"
elif [ -d "$DIR/Mector HUD.app" ]; then
    APP_TARGET="$DIR/Mector HUD.app"
elif [ -d "$HOME/Applications/Mector HUD.app" ]; then
    APP_TARGET="$HOME/Applications/Mector HUD.app"
elif [ -d "$DIR/../Mector HUD.app" ]; then
    APP_TARGET="$DIR/../Mector HUD.app"
fi

# 2. If running inside a mounted read-only DMG, auto-install to /Applications
if [[ "$APP_TARGET" == /Volumes/* ]]; then
    echo "📦 Detected Mector inside Disk Image installer."
    echo "📋 Copying 'Mector HUD.app' into your /Applications folder..."
    cp -R "$APP_TARGET" /Applications/ 2>/dev/null
    if [ -d "/Applications/Mector HUD.app" ]; then
        APP_TARGET="/Applications/Mector HUD.app"
        echo "✓ Successfully installed to /Applications/Mector HUD.app"
    fi
fi

if [ -z "$APP_TARGET" ] || [ ! -d "$APP_TARGET" ]; then
    echo "⚠️  'Mector HUD.app' not found."
    echo "👉 Please drag 'Mector HUD.app' into /Applications first, then run this again!"
    echo ""
    read -p "Press [Enter] to exit..."
    exit 1
fi

echo "📍 Target App: $APP_TARGET"
echo "🔓 Removing macOS Gatekeeper quarantine restrictions..."

# Clear quarantine and translocation extended attributes
xattr -cr "$APP_TARGET" 2>/dev/null
xattr -dr com.apple.quarantine "$APP_TARGET" 2>/dev/null

# Ensure executable permissions on Mach-O binary and launcher
chmod +x "$APP_TARGET/Contents/MacOS/MectorHUD" 2>/dev/null
chmod +x "$APP_TARGET/Contents/MacOS/launcher.sh" 2>/dev/null

echo "✓ Gatekeeper successfully unblocked!"
echo "🚀 Launching Mector HUD..."
echo ""

open "$APP_TARGET"

echo "========================================================================"
echo "✨ SUCCESS! Mector HUD is running."
echo "   Look for the '◈ M' icon in your top macOS menu bar."
echo "   You can now close this Terminal window."
echo "========================================================================"
sleep 1
