#!/bin/bash
# install_bundle_macos.sh
# Install downloaded OFX bundle to DaVinci Resolve on macOS
# Handles: quarantine removal, cache clearing, installation
# Usage: bash install_bundle_macos.sh [path_to_bundle]
#        Or drag bundle onto this script in Finder
#        With NO argument, the script installs the .ofx.bundle that sits next to
#        its own install_info folder (one directory up). This makes the README's
#        copy-paste command immune to the browser renaming a re-downloaded folder
#        to "<effect> 2", "<effect> 3", etc. — the script always resolves the
#        bundle relative to ITS OWN location, never a hardcoded ~/Downloads path.

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${CYAN}=========================================${NC}"
echo -e "${CYAN}OFX Bundle Installer for macOS${NC}"
echo -e "${CYAN}=========================================${NC}"

BUNDLE_PATH="$1"
INSTALL_DIR="/Library/OFX/Plugins"
CACHE_FILE="$HOME/Library/Application Support/Blackmagic Design/DaVinci Resolve/OFXPluginCacheV2.xml"

# No bundle argument: self-locate the .ofx.bundle shipped alongside this script.
# The download layout is  <effect>/<effect>_install_info/INSTALL.sh  with the bundle
# at  <effect>/<bundle>.ofx.bundle , so the bundle is exactly one directory up from
# this script. Resolving from the script's own path (not ~/Downloads/<effect>) is what
# makes this correct even when the parent folder was renamed to "<effect> 2".
if [ -z "$BUNDLE_PATH" ]; then
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    # Find .ofx.bundle directories one level up (the effect's download folder).
    BUNDLE_MATCHES=()
    while IFS= read -r d; do
        BUNDLE_MATCHES+=("$d")
    done < <(find "$SCRIPT_DIR/.." -maxdepth 1 -type d -name '*.ofx.bundle' 2>/dev/null)

    if [ "${#BUNDLE_MATCHES[@]}" -eq 0 ]; then
        echo -e "${RED}ERROR: no .ofx.bundle found next to this installer.${NC}"
        echo -e "${YELLOW}Drag the downloaded .ofx.bundle onto this script, or run:${NC}"
        echo -e "${YELLOW}  bash install_bundle_macos.sh <path_to_bundle>${NC}"
        exit 1
    elif [ "${#BUNDLE_MATCHES[@]}" -gt 1 ]; then
        echo -e "${RED}ERROR: multiple .ofx.bundle folders found next to this installer:${NC}"
        for d in "${BUNDLE_MATCHES[@]}"; do echo -e "${YELLOW}  $d${NC}"; done
        echo -e "${YELLOW}Pass the one you want explicitly: bash install_bundle_macos.sh <path_to_bundle>${NC}"
        exit 1
    fi
    BUNDLE_PATH="${BUNDLE_MATCHES[0]}"
    echo -e "${CYAN}Auto-detected bundle: $BUNDLE_PATH${NC}"
fi

if [ ! -d "$BUNDLE_PATH" ]; then
    echo -e "${RED}ERROR: Bundle not found: $BUNDLE_PATH${NC}"
    exit 1
fi

BUNDLE_NAME=$(basename "$BUNDLE_PATH")
echo -e "${CYAN}Installing: $BUNDLE_NAME${NC}"
echo ""

# Step 1: Check if Resolve is running
echo -e "${CYAN}[1/5] Checking if DaVinci Resolve is running...${NC}"
if pgrep -i "resolve" > /dev/null 2>&1; then
    echo -e "${RED}❌ ERROR: DaVinci Resolve is currently running!${NC}"
    echo -e "${RED}Please quit Resolve completely (Cmd+Q) and run this script again.${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Resolve not running${NC}"
echo ""

# Step 2: Remove quarantine flag
echo -e "${CYAN}[2/5] Checking quarantine status...${NC}"
if xattr -l "$BUNDLE_PATH" | grep -q "com.apple.quarantine"; then
    echo -e "${YELLOW}Removing quarantine flag...${NC}"
    xattr -dr com.apple.quarantine "$BUNDLE_PATH"

    if xattr -l "$BUNDLE_PATH" | grep -q "com.apple.quarantine"; then
        echo -e "${RED}ERROR: Failed to remove quarantine flag${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ Quarantine removed${NC}"
else
    echo -e "${GREEN}✓ Bundle not quarantined${NC}"
fi
echo ""

# Step 3: Verify bundle
echo -e "${CYAN}[3/5] Verifying bundle...${NC}"

# Check notarization (xcrun required - not available without Xcode CLI tools)
if command -v xcrun > /dev/null 2>&1; then
    if xcrun stapler validate "$BUNDLE_PATH" > /dev/null 2>&1; then
        echo -e "${GREEN}✓ Bundle is notarized${NC}"
    else
        echo -e "${YELLOW}⚠ WARNING: Bundle may not be notarized${NC}"
    fi
else
    echo -e "${YELLOW}⚠ Notarization check skipped (Xcode CLI tools not installed)${NC}"
fi

# Check code signature
if command -v codesign > /dev/null 2>&1; then
    if codesign --verify --verbose "$BUNDLE_PATH" 2>/dev/null; then
        echo -e "${GREEN}✓ Code signature valid${NC}"
    else
        echo -e "${YELLOW}⚠ WARNING: Code signature verification failed${NC}"
    fi
else
    echo -e "${YELLOW}⚠ Code signature check skipped${NC}"
fi
echo ""

# Step 4: Clear Resolve caches
echo -e "${CYAN}[4/5] Clearing DaVinci Resolve caches...${NC}"
CLEARED=0

# Clear OFX plugin cache
if [ -f "$CACHE_FILE" ]; then
    rm -f "$CACHE_FILE"
    echo -e "${GREEN}✓ OFX plugin cache cleared${NC}"
    CLEARED=$((CLEARED + 1))
fi

# Clear database cache
DB_CACHE="$HOME/Library/Caches/com.blackmagic-design.DaVinciResolve/Cache.db"*
if ls $DB_CACHE > /dev/null 2>&1; then
    rm -rf $DB_CACHE
    echo -e "${GREEN}✓ Database cache cleared${NC}"
    CLEARED=$((CLEARED + 1))
fi

if [ $CLEARED -eq 0 ]; then
    echo -e "${YELLOW}No caches found (first install?)${NC}"
fi
echo ""

# Step 5: Install bundle
echo -e "${CYAN}[5/5] Installing bundle...${NC}"

# Check if we need sudo
if [ ! -w "$INSTALL_DIR" ]; then
    echo -e "${YELLOW}Installing to $INSTALL_DIR requires administrator privileges${NC}"
    echo -e "${YELLOW}You may be prompted for your password...${NC}"
    SUDO="sudo"
else
    SUDO=""
fi

# Remove old version if exists
if [ -d "$INSTALL_DIR/$BUNDLE_NAME" ]; then
    echo -e "${YELLOW}Removing old version...${NC}"
    $SUDO rm -rf "$INSTALL_DIR/$BUNDLE_NAME"
fi

# Create install directory if needed
$SUDO mkdir -p "$INSTALL_DIR"

# Copy bundle
$SUDO cp -fr "$BUNDLE_PATH" "$INSTALL_DIR/"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Bundle installed to $INSTALL_DIR/$BUNDLE_NAME${NC}"
else
    echo -e "${RED}ERROR: Failed to install bundle${NC}"
    exit 1
fi

echo ""
echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}✅ Installation complete!${NC}"
echo -e "${GREEN}=========================================${NC}"
echo ""
echo -e "${CYAN}Next steps:${NC}"
echo -e "  1. Launch DaVinci Resolve"
echo -e "  2. The plugin will appear in the Effects Library"
echo -e "  3. Drag it onto a clip to use it"
echo ""
echo -e "${YELLOW}Note: If the plugin doesn't appear, try restarting Resolve.${NC}"
