#!/bin/bash

# Wrapper script to redirect etcd's stdout and stderr to a file and raise appropriate ENT logs
# This also uses flock(1) to ensure that only one etcd process can write the pidfile at once
# See https://tobrunet.ch/2013/01/follow-up-bash-script-locking-with-flock/ for more on Bash file locking

PIDFILE=/var/run/clearwater-etcd/clearwater-etcd.pid
PIDFILE_LOCK=/var/run/clearwater-etcd/clearwater-etcd.pid.lock

# Claim file handle 200, writing to the lock file, so we can reference it on
# the next line
exec 200>$PIDFILE_LOCK 

# Exit unless we have an exclusive lock on file handle 200 (the lock file) -
# i.e. unless no other etcd process is running
if ! flock --nonblock 200
then
  existing_pid=$(cat $PIDFILE)
  echo "Error: could not acquire lock on $PIDFILE_LOCK, pid $existing_pid holds it" >> /var/log/clearwater-etcd/clearwater-etcd.log 2>&1
  exit 99
fi

# After this point, we can be sure we're the only script running, so we can
# write to the pidfile without fear that another etcd process will start
/usr/share/clearwater/bin/ent_log.py "etcd" CL_ETCD_STARTED
echo $$ > $PIDFILE
exec /usr/share/clearwater/clearwater-etcd/2.2.5/etcd $@ >> /var/log/clearwater-etcd/clearwater-etcd.log 2>&1
rm $PIDFILE
/usr/share/clearwater/bin/ent_log.py "etcd" CL_ETCD_EXITED
