#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMMAND="${1:-}"
if [[ $# -gt 0 ]]; then
  shift
fi

STACK_NAME="${OYSTERUN_RELEASE_STACK:-production}"
FOLLOW_LOGS=0

usage() {
  cat <<'EOF'
Usage:
  tool_scripts/oysterun_release_service.sh install [--no-start]
  tool_scripts/oysterun_release_service.sh start
  tool_scripts/oysterun_release_service.sh stop
  tool_scripts/oysterun_release_service.sh restart
  tool_scripts/oysterun_release_service.sh status
  tool_scripts/oysterun_release_service.sh logs [--follow]

Release service commands target the production stack by default. Override only
for development with OYSTERUN_RELEASE_STACK=<stack>.
EOF
}

case "${COMMAND}" in
  install)
    exec "${SCRIPT_DIR}/install_oysterun_launch_agents.sh" --stack "${STACK_NAME}" "$@"
    ;;
  start)
    exec "${SCRIPT_DIR}/start_oysterun.sh" --stack "${STACK_NAME}" "$@"
    ;;
  stop)
    exec "${SCRIPT_DIR}/stop_oysterun.sh" --stack "${STACK_NAME}" "$@"
    ;;
  restart)
    exec "${SCRIPT_DIR}/restart_oysterun.sh" --stack "${STACK_NAME}" "$@"
    ;;
  status)
    exec "${SCRIPT_DIR}/status_oysterun_launch_agents.sh" --stack "${STACK_NAME}" "$@"
    ;;
  logs)
    while [[ $# -gt 0 ]]; do
      case "$1" in
        --follow|-f)
          FOLLOW_LOGS=1
          shift
          ;;
        *)
          echo "[oysterun-service] error: unknown logs argument: $1" >&2
          exit 2
          ;;
      esac
    done
    source "${SCRIPT_DIR}/oysterun_service_common.sh"
    configure_stack_runtime
    if [[ "${FOLLOW_LOGS}" -eq 1 ]]; then
      exec tail -n 200 -f "${HOST_LOG}"
    fi
    exec tail -n 200 "${HOST_LOG}"
    ;;
  ""|-h|--help|help)
    usage
    ;;
  *)
    echo "[oysterun-service] error: unknown command: ${COMMAND}" >&2
    usage >&2
    exit 2
    ;;
esac
