#!/bin/bash
: '
This is a wrapper script for the export and import queue processing.
Script 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_example.sh -o import -d mysubalias -i 1
Example2: ./scripts/queue_cron_example.sh -o import -u https://mysubscriber.com -i 1
Example1: ./scripts/queue_cron_example.sh -o export -d mypubalias -i 2
Example2: ./scripts/queue_cron_example.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

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}"
