#!/bin/bash
# GHOST Creative System - macOS installer
# v3.6.8
#
# Usage:
#   ./Install_GHOST.command                     interactive (asks where to install)
#   ./Install_GHOST.command -s                  silent, default user CEP folder
#   ./Install_GHOST.command "/Volumes/Work/GHOST"   custom install folder
#   ./Install_GHOST.command -s "/Volumes/Work/GHOST"

set -e

EXT_ID="com.ghost.creativesystem"
CEP_DIR="$HOME/Library/Application Support/Adobe/CEP/extensions"
CEP_SYSTEM_DIR="/Library/Application Support/Adobe/CEP/extensions"
BACKUP_ROOT="$HOME/Library/Application Support/GHOST Creative System/Backups"
STAMP=$(date +%Y%m%d-%H%M%S)
SOURCE_DIR="$(cd "$(dirname "$0")" && pwd)/GHOST Creative System"

SILENT=0
INSTALL_ROOT=""
for arg in "$@"; do
    case "$arg" in
        -s|--silent|/S|/s) SILENT=1 ;;
        *) INSTALL_ROOT="$arg" ;;
    esac
done

echo ""
echo "  GHOST Creative System - macOS install (v3.6.8)"
echo ""

if [ ! -d "$SOURCE_DIR" ]; then
    echo "Source folder not found: $SOURCE_DIR"
    echo "Make sure you extracted the ZIP before running this."
    exit 1
fi

if [ -z "$INSTALL_ROOT" ] && [ "$SILENT" -eq 0 ]; then
    echo "Where should GHOST be installed?"
    echo "  [1] Current user (recommended)  $CEP_DIR"
    echo "  [2] All users (needs password)  $CEP_SYSTEM_DIR"
    echo "  [3] Custom folder (a symlink is created in the CEP folder)"
    printf "Select 1-3 (Enter = 1): "
    read -r choice
    case "$choice" in
        2) INSTALL_ROOT="$CEP_SYSTEM_DIR" ;;
        3) printf "Full path (e.g. /Volumes/Work/GHOST): "; read -r INSTALL_ROOT ;;
        *) INSTALL_ROOT="$CEP_DIR" ;;
    esac
fi
[ -z "$INSTALL_ROOT" ] && INSTALL_ROOT="$CEP_DIR"

case "$INSTALL_ROOT" in
    /*) ;;
    *) echo "Install folder must be an absolute path: $INSTALL_ROOT"; exit 1 ;;
esac

SUDO=""
if [ "$INSTALL_ROOT" = "$CEP_SYSTEM_DIR" ]; then SUDO="sudo"; fi

TARGET="$INSTALL_ROOT/$EXT_ID"

$SUDO mkdir -p "$INSTALL_ROOT"
mkdir -p "$CEP_DIR"
mkdir -p "$BACKUP_ROOT"

if [ -d "$TARGET" ]; then
    echo "-> Backing up previous install to $BACKUP_ROOT/$STAMP"
    $SUDO mv "$TARGET" "$BACKUP_ROOT/$STAMP"
fi

echo "-> Installing to $TARGET"
$SUDO cp -R "$SOURCE_DIR" "$TARGET"

# Custom folder: After Effects only scans the CEP folders, so link it in
if [ "$INSTALL_ROOT" != "$CEP_DIR" ] && [ "$INSTALL_ROOT" != "$CEP_SYSTEM_DIR" ]; then
    LINK="$CEP_DIR/$EXT_ID"
    rm -rf "$LINK"
    ln -s "$TARGET" "$LINK"
    echo "-> Linked into CEP folder: $LINK"
fi

# Enable unsigned CEP extensions (CEP 9-13)
echo "-> Enabling unsigned CEP extensions"
for v in 9 10 11 12 13; do
    defaults write "com.adobe.CSXS.$v" PlayerDebugMode 1 2>/dev/null || true
done

echo ""
echo "Installed successfully: $TARGET"
echo ""
echo "   Next: Restart Adobe After Effects, then open"
echo "   Window > Extensions (Legacy) > GHOST CACHE / GHOST COMMAND / GHOST TOOLS"
echo ""
