#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${WORKSHOP_NOTIFICATION_ENV_FILE:-$ROOT/.env}"
WORKER="${WORKSHOP_NOTIFICATION_WORKER:-$ROOT/bin/workshop-notification-worker.php}"
PHP_CLI="${WORKSHOP_NOTIFICATION_PHP_CLI:-/usr/local/bin/php}"
FLOCK="${WORKSHOP_NOTIFICATION_FLOCK:-/usr/bin/flock}"
if [[ ! -r "$ENV_FILE" ]]; then
  exit 0
fi
TRANSPORT="$(awk -F= '$1 == "WORKSHOP_NOTIFICATION_TRANSPORT" {sub(/^[^=]*=/, ""); print; exit}' "$ENV_FILE")"
if [[ "$TRANSPORT" != "smtp" ]]; then
  exit 0
fi

if [[ ! -x "$PHP_CLI" ]]; then
  echo "Workshop notification worker requires PHP CLI" >&2
  exit 2
fi
PHP_SAPI="$({ "$PHP_CLI" -r 'echo PHP_SAPI;' 2>/dev/null || true; })"
if [[ "$PHP_SAPI" != "cli" ]]; then
  echo "Workshop notification worker requires PHP CLI" >&2
  exit 2
fi
if [[ ! -x "$FLOCK" ]]; then
  echo "Workshop notification worker requires flock" >&2
  exit 2
fi

export WORKSHOP_NOTIFICATION_ENV_FILE="$ENV_FILE"
exec "$FLOCK" -n /tmp/yokesen-workshop-notification.lock \
  "$PHP_CLI" "$WORKER"
