#!/bin/bash
: '
This is a wrapper script for the export and import queue processing.
Script has frequency to run queue every 1 minute, it accepts below arguments.
  -o : This is the import or export operation to be performed on queue.
  -d : This is drush alias of the site.
  -u : This is uri of the site.
  -i : Index of the flock file. default value is 0.

Example1: ./scripts/queue_cron.sh -o import -d mysubalias -i 1
Example2: ./scripts/queue_cron.sh -o import -u https://mysubscriber.com -i 1
Example1: ./scripts/queue_cron.sh -o export -d mypubalias -i 2
Example2: ./scripts/queue_cron.sh -o export -u https://mypublisher.com -i 2
'
while getopts d:u:i:o: flag
do
  case "${flag}" in
      d) drushalias=${OPTARG};;
      u) uri=${OPTARG};;
      i) index=${OPTARG};;
      o) operation=${OPTARG};;
  esac
done

# Checking for flock file index, default value = 0.
if [ -z "$index" ]; then
  echo "Flock file index is empty, setting default value to 0"
  index=0
fi

# Checking if valid -o (operation) is passed.
queue_command=''
flock_file_name=''
if [ "$operation" == "import" ]; then
  queue_command="ach-import"
  flock_file_name="achim${index}.lck"
elif [ "$operation" == "export" ]; then
  queue_command="ach-export"
  flock_file_name="achex${index}.lck"
else
  echo "Invalid queue operation"
  exit
fi

# Drush alias takes precedence over site uri.
site_identifier="";
if [ -n "$drushalias" ]; then
  site_identifier="@${drushalias}"
elif [ -n "$uri" ]; then
  site_identifier="-l ${uri}"
else
  echo "Enter drush alias or site uri."
  exit
fi

# The end timestamp is now + 300 seconds (5 minutes).
end=$(( $(date +%s) + 300 ))

while : ; do
start=$(date +%s)

flock -xn /mnt/gfs/${AH_SITE_NAME}/files-private/${flock_file_name} -c "drush ${site_identifier} -r /var/www/html/${AH_SITE_NAME}/docroot ${queue_command}"

# Ensure it does not run more frequently than once
# per minute by sleeping if the command takes less
# than a minute to execute.
sleep $(( 60 - $(date +%s) + $start ))

# Exit the loop if the current timestamp exceeds the
# end timestamp.
[ $(date +%s) -lt $end ] || break
done
