#! /bin/bash
# Nathalie - 2016-06-17

capistrano_path=/home/pix/capistrano/pixways
features_folder=/var/www/pix/current/public/features
temp_features_folder=/var/www/pix/current/public/features/temp
archive_features_folder=/var/www/pix/current/public/features/archive
file_type="*.json"

#check if program is already running
if [ $(ps hf -opid,cmd -C send_features.sh | awk '$2 !~ /^[|\\]/ { print $1 }'|wc -l) -le 1 ]; then
    #check if new json files are waiting to be sent to servers
    if [ -n "$(ls $features_folder/$file_type 2> /dev/null)" ]; then
       #move json file(s) into a temp folder
       mkdir -p $temp_features_folder
       for f in $features_folder/$file_type
       do
           mv $f $temp_features_folder
       done
    fi

    #call the send_feature task on the servers
    cd $capistrano_path/FR/
    ./mega_cap_lessverbose "pixpalace:send_features"
    cd $capistrano_path/TESTS/
    ./mega_cap_lessverbose "pixpalace:send_features"

    #move json files from the temp folder into the archive folder
    if [ -n "$(ls $temp_features_folder/$file_type 2> /dev/null)" ]; then
       mkdir -p $archive_features_folder
       for f in $temp_features_folder/$file_type
       do
           mv $f $archive_features_folder
       done
    fi
fi