#!/bin/bash

# Exit codes:
# 0: Script finished normally
# 1: Process already running
# 2: Error reading config-file
# 3: Error writing to pid-dir

# Where do we live, and what's our config file?
MYSELF=$(basename ${0})
LIVEDIR=$(dirname $(readlink -f ${0}))
CONFFILE=${LIVEDIR}/${MYSELF%.*}.conf

# Look for our config-file. Exit if it's missing.
if [ ! -r "${CONFFILE}" ]
then
	echo "Error: Unable to read config-file ${CONFFILE} - make sure it exists and is readable."
	exit 2
fi

# Source the config-file
. ${CONFFILE}

# Make sure we can write to the pid-dir
if [ ! -w "${PIDDIR}" ]
then
	echo "Error: Unable to write to pid-dir ${PIDDIR} - make sure it exists and is writeable."
	exit 3
fi

# Check for existing pidfile for this program
if [ ! -f ${PIDDIR}/${MYSELF}.pid ]
then
	# No pid-file, create one with our pid
	echo ${$} > ${PIDDIR}/${MYSELF}.pid
else
	# pid-file exist, check if the pid is running as ourselves
	ps -p $(cat ${PIDDIR}/${MYSELF}.pid) -f | grep ${MYSELF} > /dev/null 2>&1
	if [ ${?} -eq 1 ]
	then
		# Pid running our script not found, recreate pid-file and carry on
		logger -i -t ${MYSELF} "Cannot find my supposedly running clone, recreating pid-file and carrying on."
		echo ${$} > ${PIDDIR}/${MYSELF}.pid
	else
		# Pid running our script was found, exit immediately
		logger -i -t ${MYSELF} "Process already running as pid $(cat ${PIDDIR}/${MYSELF}.pid). Exiting"
		exit 1
	fi
fi

# Put your code here

# Remove pidfile as script ends
rm -f ${PIDDIR}/${MYSELF}.pid

