#!/bin/sh

##
# This script is provided as an example launcher script
# for using spawn-fcgi with systemd.
#
# Copy this script to /usr/libexec/spawn-fcgi_launcher
# And make sure it's executable
##

if [ -z "$1" ]; then
    echo "Usage: $0 configuration_file"
    exit 1
fi

# Config file
CONF_FILE="/etc/spawn-fcgi/${1}.conf"

# ABSOLUTE path to the spawn-fcgi binary
SPAWNFCGI="/usr/bin/spawn-fcgi"

# Read settings from config file if it exists
[ -e "${CONF_FILE}" ] && . "${CONF_FILE}"

if [ -z "$USERID" ]; then
    echo "USERID not set"
    exit 1
fi

if [ -z "$GROUPID" ]; then
    echo "USERID not set"
    exit 1
fi

if [ -z "$FCGIPORT" ]; then
    echo "FCGIPORT not set"
    exit 1
fi

if [ -z "$FCGIPROGRAM" ]; then
    echo "FCGIPROGRAM not set"
    exit 1
fi

# Check user existence
if [ ! $(id -u ${USERID} &> /dev/null) ]; then
    echo ;
    echo "User ${USERID} does not exist! Check what you use the correct USERID."
    exit 1
fi

# Check group existence
if [ ! $(id -g ${GROUPID} &> /dev/null) ]; then
    echo ;
    echo "Group ${GROUPID} does not exist! Check what you use the correct GROUPID."
    exit 1
fi

# Execute spawn-fcgi with its options
env - ${SPAWNFCGI} -p ${FCGIPORT} -f ${FCGIPROGRAM} -u ${USERID} -g ${GROUPID}

