#!/bin/sh
# start_memcached_and_run.sh - start a memcached instance, inspired fromruby-mysql2
# It is in turn inspired by
# debian/test_mysql.sh from libdbi-drivers source package.

set -e

MEMCACHED_USER=nobody
MEMCACHED_PORT=11211

## Start memcached
#/usr/bin/memcached -u ${MEMCACHED_USER} &
#PID=$!
# start memcached only if nothing is listening on MEMCACHED_PORT
if ! ss -ltnp "sport = :${MEMCACHED_PORT}" 2>/dev/null | grep -q memcached; then
  /usr/bin/memcached -u "$MEMCACHED_USER" -p "$MEMCACHED_PORT" 2>/dev/null &
  PID=$!
  # small delay to avoid race (ensure daemon is ready)
  sleep 2
fi

"$@"

 cleanup() {
  # Stop memcached
  if [ -n "$PID" ]; then
    kill -0 "$PID" 2>/dev/null && kill -9 "$PID" 2>/dev/null || true
  fi
 }
 trap cleanup EXIT INT TERM ALRM
