#!/bin/sh

PRODUCT_DIR='Neat Video for After Effects'
PRODUCT_NAME="NeatVideo.plugin"
ALIAS_NAME="NeatVideo alias"
LIBRARY_DIR="/Library"
SYMLINKED_LIST=""

oldIFS=$IFS
IFS=$'\n'
for AE_APP in $(find /Applications \( -name 'Adobe After Effects CS*.app' \) -maxdepth 4 -print)
do
    if [ ${AE_APP} != ${AE_APP/CS\.app/} ] ||
       [ ${AE_APP} != ${AE_APP/CS2\.app/} ]
    then
        # support only AE CS3 and later
        continue
    fi

    PLUGIN_DIR="${AE_APP%/*}/Plug-ins"
    if [ -a "${PLUGIN_DIR}" ]
    then
        if [ -a "${PLUGIN_DIR}/${PRODUCT_NAME}" ]
        then
            rm -Rf "${PLUGIN_DIR}/${PRODUCT_NAME}"
        fi

        if [ -a "${PLUGIN_DIR}/${ALIAS_NAME}" ]
        then
            rm -Rf "${PLUGIN_DIR}/${ALIAS_NAME}"
        fi

        ln -sf "${2}/${PRODUCT_DIR}/${PRODUCT_NAME}" \
               "${PLUGIN_DIR}/${PRODUCT_NAME}"

        SYMLINKED_LIST="${SYMLINKED_LIST}|${PLUGIN_DIR}"
   fi
done
IFS=$oldIFS

# write init dir
SYS_PLIST='/Library/Preferences/com.absoft.NeatVideo AE'
defaults write "${SYS_PLIST}" InitDir "${2}/${PRODUCT_DIR}"

# increment install ID
INSTALL_ID=$(defaults read "${SYS_PLIST}" InstallID 2> /dev/null)
if [ $? == 0 ]
then
  defaults write "${SYS_PLIST}" InstallID $((INSTALL_ID + 1))
else
  defaults write "${SYS_PLIST}" InstallID "1"
fi

if [ -z "${SYMLINKED_LIST}" ]
then
    "$1/Contents/Resources/msg" "Unable to find the location of After Affects folder automatically" \
    "To manually install the plug-in:\
    |1. create an alias for Neat Image plug-in\
    |(/Applications/Neat Video for After Effects/NeatVideo.plugin).\
    |2. copy that alias to the /Plug-ins/ sub-folder in After Effects folder (for example, in case of AE CS5:\
    |/Applications/Adobe After Effects CS5/Plug-ins/).\
    |3. restart After Effects.\
    |That should make Neat Video plug-in visible in After Effects."
else
    "$1/Contents/Resources/msg" "Plugin successfully added to the following location(s):" "${SYMLINKED_LIST}" "|"
fi
