#!/bin/sh
set -eu

recipe=${LEMC_RECIPE_NAME:-page}
kind=${LEMC_CALLBACK_KIND:-now}
private_dir=${LEMC_PRIVATE_DIR:-/lemc/private}
state_root="$private_dir/tutorial-06"
mkdir -p "$state_root"

emit() {
  printf 'lemc.output;callback tutorial recipe=%s phase=%s result=%s\n' \
    "$recipe" "$kind" "$1"
}

case "$kind" in
  on_action)
    emit accepted
    ;;
  before_run)
    emit prepared
    ;;
  after_run)
    emit verified
    ;;
  on_deactivate)
    if [ "$recipe" = "retryable-cleanup" ]; then
      marker="$state_root/retryable-cleanup.attempted"
      if [ ! -f "$marker" ]; then
        : > "$marker"
        echo "intentional first cleanup failure" >&2
        exit 42
      fi
      rm -f "$marker" "$state_root/retryable-cleanup.active"
      emit retried-and-removed
      exit 0
    fi
    rm -f "$state_root/$recipe.active"
    emit removed
    ;;
  now)
    : > "$state_root/$recipe.active"
    emit completed
    ;;
  *)
    echo "unsupported callback kind" >&2
    exit 64
    ;;
esac
