#!/bin/bash
# install_bundle_linux.sh
# Install downloaded OFX bundle to DaVinci Resolve on Linux
# Handles: Resolve detection, cache clearing, installation
# Usage: bash INSTALL.sh <path_to_bundle>
#        Or: sudo bash INSTALL.sh <path_to_bundle>

# 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 Linux${NC}"
echo -e "${CYAN}=========================================${NC}"

BUNDLE_PATH="$1"
INSTALL_DIR="/usr/OFX/Plugins"
CACHE_FILE="$HOME/.local/share/DaVinciResolve/configs/OFXPluginCacheV2.xml"

# If no bundle path provided, self-locate the .ofx.bundle next to THIS script.
# Resolve from the script's OWN directory (not the caller's cwd) so it works no
# matter where it's invoked from (e.g. `sudo bash /path/INSTALL.sh` from elsewhere,
# or dragged into a terminal). Refuse to guess on zero OR multiple matches: a
# coexisting-version download can leave several bundles side by side, and silently
# installing the wrong one is exactly the stale-version trap.
if [ -z "$BUNDLE_PATH" ]; then
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    BUNDLE_COUNT=$(find "$SCRIPT_DIR" -maxdepth 1 -type d -name "*.ofx.bundle" | wc -l)
    if [ "$BUNDLE_COUNT" -eq 0 ]; then
        echo -e "${RED}ERROR: No .ofx.bundle found next to this script ($SCRIPT_DIR)${NC}"
        echo -e "${YELLOW}Usage: bash INSTALL.sh <path_to_bundle>${NC}"
        exit 1
    elif [ "$BUNDLE_COUNT" -gt 1 ]; then
        echo -e "${RED}ERROR: Multiple .ofx.bundle folders found next to this script — refusing to guess which to install:${NC}"
        find "$SCRIPT_DIR" -maxdepth 1 -type d -name "*.ofx.bundle" | sed 's/^/  /'
        echo -e "${YELLOW}Run with an explicit path: bash INSTALL.sh <path_to_bundle>${NC}"
        exit 1
    fi
    BUNDLE_PATH=$(find "$SCRIPT_DIR" -maxdepth 1 -type d -name "*.ofx.bundle")
    echo -e "${YELLOW}Found 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/4] 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 and run this script again.${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Resolve not running${NC}"
echo ""

# Step 2: Verify bundle structure
echo -e "${CYAN}[2/4] Verifying bundle structure...${NC}"
LINUX_PATH="$BUNDLE_PATH/Contents/Linux-x86-64"
if [ -d "$LINUX_PATH" ]; then
    OFX_COUNT=$(find "$LINUX_PATH" -name "*.ofx" | wc -l)
    if [ "$OFX_COUNT" -gt 0 ]; then
        echo -e "${GREEN}✓ Bundle structure valid ($OFX_COUNT .ofx file(s) found)${NC}"
    else
        echo -e "${YELLOW}⚠ WARNING: No .ofx files found in Contents/Linux-x86-64${NC}"
    fi
else
    echo -e "${RED}ERROR: Contents/Linux-x86-64 folder not found${NC}"
    echo -e "${RED}This bundle may not be built for Linux.${NC}"
    exit 1
fi
echo ""

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

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

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

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

# Check if we need sudo
if [ ! -w "$INSTALL_DIR" ] && [ "$(id -u)" -ne 0 ]; then
    echo -e "${YELLOW}Installing to $INSTALL_DIR requires root privileges${NC}"
    echo -e "${YELLOW}Please run: sudo bash INSTALL.sh $BUNDLE_PATH${NC}"
    exit 1
fi

# Create install directory if needed
if [ ! -d "$INSTALL_DIR" ]; then
    echo -e "${YELLOW}Creating $INSTALL_DIR...${NC}"
    mkdir -p "$INSTALL_DIR"
fi

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

# Copy bundle
cp -r "$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}"
