#!/usr/bin/env bash

set -Eeuo pipefail
umask 077

remote_path="${1:-}"

case "$remote_path" in
  /*) ;;
  *) echo "Scheduler requires an absolute application path." >&2; exit 1 ;;
esac
remote_path="${remote_path%/}"
test -n "$remote_path"
test "$remote_path" != "/"
printf '%s' "$remote_path" | grep -Eq '^/[a-zA-Z0-9_./-]+$'
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)"
printf '%s' "$remote_path" | grep -Eq '^/[a-zA-Z0-9_./-]+$'
php_binary="$(command -v php)"
printf '%s' "$php_binary" | grep -Eq '^/[a-zA-Z0-9_./-]+$'
command -v crontab > /dev/null
cd "$remote_path"

legacy_pid_path="$remote_path/.deploy/workers/scheduler.pid"
if [ -L "$legacy_pid_path" ]; then
  echo "Production cron refuses a symbolic-link legacy PID file." >&2
  exit 1
fi
if [ -f "$legacy_pid_path" ]; then
  legacy_pid="$(cat "$legacy_pid_path")"
  printf '%s' "$legacy_pid" | grep -Eq '^[1-9][0-9]*$'
  if kill -0 "$legacy_pid" 2>/dev/null; then
    legacy_cwd="$(readlink "/proc/$legacy_pid/cwd" 2>/dev/null || true)"
    legacy_command="$(tr '\0' ' ' < "/proc/$legacy_pid/cmdline" 2>/dev/null || true)"
    test "$legacy_cwd" = "$remote_path"
    case "$legacy_command" in
      *"scripts/production-scheduler-loop.sh"*|*"artisan schedule:work"*) ;;
      *) echo "Legacy scheduler PID belongs to an unexpected process." >&2; exit 1 ;;
    esac
    kill "$legacy_pid"
    for attempt in 1 2 3 4 5 6 7 8 9 10; do
      if ! kill -0 "$legacy_pid" 2>/dev/null; then
        break
      fi
      sleep 1
    done
    if kill -0 "$legacy_pid" 2>/dev/null; then
      echo "The legacy scheduler did not stop safely." >&2
      exit 1
    fi
  fi
  rm -f -- "$legacy_pid_path"
fi

scheduler_log="$remote_path/storage/logs/scheduler-cron.log"
queue_log="$remote_path/storage/logs/queue-worker-default.log"
marketing_queue_log="$remote_path/storage/logs/queue-worker-marketing.log"
marketing_lock_path="$remote_path/.deploy/workers/marketing-cron.lock"
marketing_queue_enabled=0
protected_paths=("$scheduler_log" "$queue_log")
if php artisan config:show queue.connections.marketing > /dev/null 2>&1; then
  marketing_queue_enabled=1
  flock_binary="$(command -v flock)"
  printf '%s' "$flock_binary" | grep -Eq '^/[a-zA-Z0-9_./-]+$'
  protected_paths+=("$marketing_queue_log" "$marketing_lock_path")
fi
for protected_path in "${protected_paths[@]}"; do
  if [ -L "$protected_path" ]; then
    echo "Production cron refuses symbolic-link state files." >&2
    exit 1
  fi
done
touch "${protected_paths[@]}"
chmod 0600 "${protected_paths[@]}"

begin_marker='# BEGIN VIDA MANSA WHOLESALE MANAGED'
end_marker='# END VIDA MANSA WHOLESALE MANAGED'
existing_crontab="$(crontab -l 2>/dev/null || true)"
temporary_crontab="$(mktemp)"
trap 'rm -f -- "$temporary_crontab"' EXIT

printf '%s\n' "$existing_crontab" | awk \
  -v begin_marker="$begin_marker" \
  -v end_marker="$end_marker" '
    $0 == begin_marker {
      if (managed) exit 41
      managed = 1
      next
    }
    $0 == end_marker {
      if (! managed) exit 42
      managed = 0
      next
    }
    ! managed { print }
    END { if (managed) exit 43 }
  ' > "$temporary_crontab"

{
  printf '%s\n' "$begin_marker"
  printf "* * * * * cd %s && %s artisan schedule:run --no-interaction >> %s 2>&1\n" \
    "$remote_path" "$php_binary" "$scheduler_log"
  printf "* * * * * cd %s && %s artisan queue:work database --queue=default --stop-when-empty --max-time=50 --sleep=1 --tries=3 --backoff=10 --timeout=45 --no-interaction >> %s 2>&1\n" \
    "$remote_path" "$php_binary" "$queue_log"
  if [ "$marketing_queue_enabled" -eq 1 ]; then
    printf "* * * * * cd %s && %s -n %s %s artisan queue:work marketing --queue=marketing --stop-when-empty --max-time=50 --sleep=1 --tries=25 --backoff=120 --timeout=900 --no-interaction >> %s 2>&1\n" \
      "$remote_path" "$flock_binary" "$marketing_lock_path" "$php_binary" "$marketing_queue_log"
  fi
  printf '%s\n' "$end_marker"
} >> "$temporary_crontab"

chmod 0600 "$temporary_crontab"
crontab "$temporary_crontab"

installed_crontab="$(crontab -l)"
test "$(printf '%s\n' "$installed_crontab" | grep -Fxc "$begin_marker")" -eq 1
test "$(printf '%s\n' "$installed_crontab" | grep -Fxc "$end_marker")" -eq 1
test "$(printf '%s\n' "$installed_crontab" | grep -Fc 'artisan schedule:run --no-interaction')" -eq 1
test "$(printf '%s\n' "$installed_crontab" | grep -Fc 'artisan queue:work database --queue=default')" -eq 1
if [ "$marketing_queue_enabled" -eq 1 ]; then
  test "$(printf '%s\n' "$installed_crontab" | grep -Fc 'artisan queue:work marketing --queue=marketing')" -eq 1
else
  test "$(printf '%s\n' "$installed_crontab" | grep -Fc 'artisan queue:work marketing --queue=marketing')" -eq 0
fi

echo "Production scheduler and queue cron installed."
