#!/usr/bin/env bash

set -Eeuo pipefail
umask 077

remote_path="${1:-}"
queue_name="${2:-default}"

case "$remote_path" in
  /*) ;;
  *) echo "Queue worker requires an absolute application path." >&2; exit 1 ;;
esac
remote_path="${remote_path%/}"
test -n "$remote_path"
test "$remote_path" != "/"
printf '%s' "$queue_name" | grep -Eq '^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$'
test -f "$remote_path/artisan"
test -f "$remote_path/vendor/autoload.php"
test -d "$remote_path/storage/logs"

remote_path="$(cd -P "$remote_path" && pwd)"
worker_directory="$remote_path/.deploy/workers"
worker_pid_path="$worker_directory/$queue_name.pid"
worker_log_path="$remote_path/storage/logs/queue-worker-$queue_name.log"

mkdir -p "$worker_directory"
chmod 0700 "$worker_directory"
if [ -L "$worker_pid_path" ] || [ -L "$worker_log_path" ]; then
  echo "Queue worker refuses symbolic-link state files." >&2
  exit 1
fi

if [ -f "$worker_pid_path" ]; then
  previous_pid="$(cat "$worker_pid_path")"
  printf '%s' "$previous_pid" | grep -Eq '^[1-9][0-9]*$'
  if kill -0 "$previous_pid" 2>/dev/null; then
    previous_cwd="$(readlink "/proc/$previous_pid/cwd" 2>/dev/null || true)"
    previous_command="$(tr '\0' ' ' < "/proc/$previous_pid/cmdline" 2>/dev/null || true)"
    case "$previous_command" in
      *"artisan queue:work"*"--queue=$queue_name"*) ;;
      *) echo "Queue worker PID belongs to an unexpected process." >&2; exit 1 ;;
    esac
    test "$previous_cwd" = "$remote_path"
  fi
fi

cd "$remote_path"
touch "$worker_log_path"
chmod 0600 "$worker_log_path"
nohup php artisan queue:work \
  --queue="$queue_name" \
  --sleep=3 \
  --tries=3 \
  --backoff=10 \
  --timeout=120 \
  >> "$worker_log_path" 2>&1 < /dev/null &
worker_pid="$!"
printf '%s' "$worker_pid" | grep -Eq '^[1-9][0-9]*$'

sleep 5
kill -0 "$worker_pid"
worker_cwd="$(readlink "/proc/$worker_pid/cwd")"
worker_command="$(tr '\0' ' ' < "/proc/$worker_pid/cmdline")"
test "$worker_cwd" = "$remote_path"
case "$worker_command" in
  *"artisan queue:work"*"--queue=$queue_name"*) ;;
  *) echo "The production queue worker command could not be verified." >&2; exit 1 ;;
esac

worker_pid_temporary="$worker_pid_path.tmp.$$"
printf '%s\n' "$worker_pid" > "$worker_pid_temporary"
chmod 0600 "$worker_pid_temporary"
mv "$worker_pid_temporary" "$worker_pid_path"

echo "Production queue worker started for $queue_name."
