################################################################################
#
# This script is invokved by Any Tag > Import Keywords via this command
# line:
#
# open -a Terminal.app <script>
#
# which opens it in a new window. Any Tag replaces these tokens:
#
# {PLUGIN} -- full path to the plugin folder (containing this script)
# {CATALOG} -- full path to the catalog .lrcat file
# {SQL} -- full path to the temp file containing SQL commands to be executed
#
# (Arguments passed to "open -a Terminal.app --args ..." aren't passed 
# to the script.
#
################################################################################

    # Change the title of the window and move it to (100, 100)
echo -n -e "\033]0;Any Tag > Import Keywords -- Apply Keyword Updates\007"
echo -n -e '\033[3;100;100t'
clear

printf "\n\n\n"
echo "Any Tag will apply your keyword updates to the Lightroom catalog."
printf "\n\n\n"

    # Wait until LR has exited and the user types Return
while [[ 1 ]]; do
    echo -n "Exit Lightroom, wait for it to exit fully, and then type Return:"
    read dummy
    if [[ ! -e "{CATALOG}.lock" ]]; then break; fi
    echo "Lightroom is still running!"
    done

    # Run the SQL commands
"{PLUGIN}"/sqlite3 "{CATALOG}" < "{SQL}"

    # Check the result
if [[ $? -ne 0 ]]; then 
    printf "\n\n\n"
    echo "A problem has occurred applying the keyword updates. Please copy and"
    echo "paste the entire contents of this window into an email to Any Tag"
    echo "support: ellis-lightroom@johnrellis.com."
else
    printf "\n\n\n" 
    echo "Keyword updates successfully applied."
    printf "\n\n\n" 
    echo "You may close this window and restart Lightroom."
    fi
printf "\n\n\n\n\n\n"
