#!/bin/bash
#
#chkconfig: - 99 01
#description: controls Frontier services

if [ -f /etc/init.d/functions ]; then
    . /etc/init.d/functions
else
    PATH="/sbin:/usr/sbin:/bin:/usr/bin"
    export PATH
fi

MYNAME="`basename $0`"

if [ -f /etc/sysconfig/$MYNAME ]; then
    . /etc/sysconfig/$MYNAME
fi

FRONTIER_USER=squid
FDLIMIT="`runuser -s /bin/bash $FRONTIER_USER -c "ulimit -Hn"`"
if [ $FDLIMIT -lt 4096 ] && [ "$1" = start ]; then
    echo "ERROR: $FRONTIER_USER hard nofile ulimit must be at least 4096" >&2
    exit 1
elif [ $FDLIMIT -gt 65536 ] || [ $FDLIMIT = "unlimited" ]; then
    FDLIMIT=65536 
    ulimit -n $FDLIMIT
fi
let BACKLOGMAX=$FDLIMIT/4
if [ "`sysctl -n net.core.somaxconn`" -lt $BACKLOGMAX ]; then
    # redirect errors to dev null because this does not work inside of
    #   docker containers
    sysctl -q -w net.core.somaxconn=$BACKLOGMAX 2>/dev/null
fi

case "$1" in
    *start)
	# require user home directory to exist because otherwise cron will
	#   fail to run user's log cleaning jobs on RHEL6 
	eval FRONTIER_HOME=~${FRONTIER_USER}
	if [ ! -d $FRONTIER_HOME ]; then
	    echo "ERROR: $FRONTIER_USER login home directory $FRONTIER_HOME does not exist" >&2
	    exit 1
	fi
	# make sure /var/run/squid exists, because on some systemd systems
	#   it might not yet be there
	if [ ! -d /var/run/squid ]; then
	    mkdir /var/run/squid
	    chown $FRONTIER_USER /var/run/squid
	    chmod 755 /var/run/squid
	fi
	;;
esac

runuser -s /bin/bash $FRONTIER_USER /usr/sbin/fn-local-squid.sh $1
