#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

: "${OYSTERUN_STACK:=production}"

source "${SCRIPT_DIR}/oysterun_service_common.sh"

ALLOW_OPERATION_ID="${OYSTERUN_LIFECYCLE_OPERATION_ID:-}"
EXPECTED_RETAINED_CURRENT_HOST_CWD=""
EXPECTED_TARGET_SERVICE_DEFINITION_SHA256=""
SERVICE_ARGS=()
while [[ $# -gt 0 ]]; do
  case "$1" in
    --expected-retained-current-host-cwd)
      [[ $# -ge 2 ]] || { echo "[oysterun-service] error: --expected-retained-current-host-cwd requires a value" >&2; exit 2; }
      EXPECTED_RETAINED_CURRENT_HOST_CWD="$2"
      shift 2
      ;;
    --expected-target-service-definition-sha256)
      [[ $# -ge 2 ]] || { echo "[oysterun-service] error: --expected-target-service-definition-sha256 requires a value" >&2; exit 2; }
      [[ -n "${ALLOW_OPERATION_ID}" ]] || { echo "[oysterun-service] error: target service-definition authority requires a receipt-bound lifecycle operation" >&2; exit 2; }
      EXPECTED_TARGET_SERVICE_DEFINITION_SHA256="$2"
      shift 2
      ;;
    *)
      SERVICE_ARGS+=("$1")
      shift
      ;;
  esac
done

if [[ "${#SERVICE_ARGS[@]}" -gt 0 ]]; then
  parse_common_args "${SERVICE_ARGS[@]}"
else
  parse_common_args
fi
configure_stack_runtime

EXPECTED_HOST_PID="$(pid_from_file "${HOST_PID_FILE}" || true)"
if [[ -z "${EXPECTED_HOST_PID}" ]]; then
  EXPECTED_HOST_PID="$(origin_host_pid_from_file "${HOST_ORIGIN_FILE}" || true)"
fi

preflight_host_restart_readiness \
  "${EXPECTED_HOST_PID}" \
  "${ALLOW_OPERATION_ID}" \
  "${EXPECTED_RETAINED_CURRENT_HOST_CWD}" \
  "" \
  "${EXPECTED_TARGET_SERVICE_DEFINITION_SHA256}"

if [[ "${#SERVICE_ARGS[@]}" -gt 0 ]]; then
  if ! "${SCRIPT_DIR}/stop_oysterun.sh" "${SERVICE_ARGS[@]}"; then
    printf '[oysterun-service] P226_CHECK stage=stop check=canonical_service_stop result=failed code=service_stop_failed\n' >&2
    exit 1
  fi
  printf '[oysterun-service] P226_CHECK stage=stop check=canonical_service_stop result=passed code=service_stop_completed\n'
  if ! "${SCRIPT_DIR}/start_oysterun.sh" "${SERVICE_ARGS[@]}"; then
    printf '[oysterun-service] P226_CHECK stage=start check=canonical_service_start result=failed code=service_start_failed\n' >&2
    exit 1
  fi
else
  if ! "${SCRIPT_DIR}/stop_oysterun.sh"; then
    printf '[oysterun-service] P226_CHECK stage=stop check=canonical_service_stop result=failed code=service_stop_failed\n' >&2
    exit 1
  fi
  printf '[oysterun-service] P226_CHECK stage=stop check=canonical_service_stop result=passed code=service_stop_completed\n'
  if ! "${SCRIPT_DIR}/start_oysterun.sh"; then
    printf '[oysterun-service] P226_CHECK stage=start check=canonical_service_start result=failed code=service_start_failed\n' >&2
    exit 1
  fi
fi
printf '[oysterun-service] P226_CHECK stage=start check=canonical_service_start result=passed code=service_start_completed\n'
