#!/bin/bash

# Clear terminal screen
clear

# Navigate to the script's directory (handles double-click execution path context)
cd "$(dirname "$0")"

echo "===================================================="
echo "  Assetszy macOS DaVinci Resolve Plugin Installer"
echo "===================================================="
echo ""

# Define macOS Target Directory paths
INSTALL_DIR="/Library/Application Support/Blackmagic Design/DaVinci Resolve/Workflow Integration Plugins/com.assetszy.resolve.plugin"

echo "Target Destination: $INSTALL_DIR"
echo "Creating directory structures (requires administrator password)..."
sudo mkdir -p "$INSTALL_DIR"

# Clean old installation if exists
if [ -d "$INSTALL_DIR" ]; then
    sudo rm -rf "$INSTALL_DIR"
    sudo mkdir -p "$INSTALL_DIR"
fi

# Copy all compilation assets
echo "Copying secure plugin bundles..."
if [ -d "dist-plugin" ]; then
    sudo cp -R dist-plugin/* "$INSTALL_DIR/"
else
    # Fallback to copy current folder assets if distributed as standalone package
    sudo cp -R * "$INSTALL_DIR/" 2>/dev/null
fi

# Copy native macOS WorkflowIntegration.node from DaVinci Resolve Developer SDK if available
SDK_NODE="/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Workflow Integrations/Examples/SamplePlugin/WorkflowIntegration.node"
if [ -f "$SDK_NODE" ]; then
    echo "Copying native macOS WorkflowIntegration.node module..."
    sudo cp "$SDK_NODE" "$INSTALL_DIR/"
else
    # Remove Windows C++ native binary if it exists in the folder (as it won't run on macOS)
    if [ -f "$INSTALL_DIR/WorkflowIntegration.node" ]; then
        echo "Removing Windows binary..."
        sudo rm "$INSTALL_DIR/WorkflowIntegration.node"
    fi
    echo "WARNING: Native macOS WorkflowIntegration.node binary not found in Developer SDK!"
    echo "Please ensure the DaVinci Resolve Developer SDK is installed on this Mac."
fi

# Clear macOS Gatekeeper Quarantine flag for all copied files to prevent unsigned app errors
echo "Bypassing macOS security Gatekeeper quarantine..."
if [ -d "$INSTALL_DIR" ]; then
    sudo xattr -cr "$INSTALL_DIR" 2>/dev/null
    sudo chmod -R 755 "$INSTALL_DIR" 2>/dev/null
    echo "[SUCCESS] Gatekeeper quarantine cleared for Assetszy!"
fi

echo ""
echo "===================================================="
echo "  Assetszy Plugin Installed Successfully on macOS!"
echo "  Please restart DaVinci Resolve Studio."
echo "  Open via: Workspace > Workflow Integrations"
echo "===================================================="
echo ""
echo "Press [Enter] to exit..."
read -r
