#!/bin/sh
###############################################################################
#                                                                             #
# IPFire.org - A linux based firewall                                         #
# Copyright (C) 2007-2022  IPFire Team  <info@ipfire.org>                     #
#                                                                             #
# This program is free software: you can redistribute it and/or modify        #
# it under the terms of the GNU General Public License as published by        #
# the Free Software Foundation, either version 3 of the License, or           #
# (at your option) any later version.                                         #
#                                                                             #
# This program is distributed in the hope that it will be useful,             #
# but WITHOUT ANY WARRANTY; without even the implied warranty of              #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               #
# GNU General Public License for more details.                                #
#                                                                             #
# You should have received a copy of the GNU General Public License           #
# along with this program.  If not, see <http://www.gnu.org/licenses/>.       #
#                                                                             #
###############################################################################

. /etc/sysconfig/rc
. $rc_functions

chown -R squid:squid /var/log/squid
chown -R squid:squid /var/log/squidGuard


transparent() {
		DEVICE=$1

		eval $(/usr/local/bin/readhash /var/ipfire/ethernet/settings)
		eval $(/usr/local/bin/readhash /var/ipfire/proxy/settings)

		# If the proxy port is not set we set the default to 800.
		if [ -z "${TRANSPARENT_PORT}" ]; then
			TRANSPARENT_PORT=800
		fi

		LOCALIP=`cat /var/ipfire/red/local-ipaddress | tr -d \n`
		if [ -z $LOCALIP ]; then
			boot_mesg "Couldn't read local-ipaddress" ${FAILURE}
			exit 1
		fi

		COUNT=1
		FILE=/var/ipfire/vpn/config

		while read LINE; do
			let COUNT=$COUNT+1
			CONN_TYPE=`echo "$LINE" | awk -F, '{ print $5 }'`
			if [ "$CONN_TYPE" != "net" ]; then
				continue
			fi
		iptables -t nat -A SQUID -i $1 -p tcp -d `echo "$LINE" | awk -F, '{ print $13 }'` --dport 80 -j RETURN
		done < $FILE

		if [ "$RED_TYPE" == "STATIC" ]; then
			iptables -t nat -A SQUID -i $1 -p tcp -d $RED_NETADDRESS/$RED_NETMASK --dport 80 -j RETURN
		fi

		iptables -t nat -A SQUID -i $1 -p tcp -d $LOCALIP --dport 80 -j RETURN

		iptables -t nat -A SQUID -i $1 -p tcp --dport 80 -j REDIRECT --to-port "${TRANSPARENT_PORT}"
}

case "$1" in
	start)
		ulimit -n 32768
		getpids "squid"

		if [ -n "${pidlist}" ]; then
			echo -e "Squid is already running with Process"\
				"ID(s) ${pidlist}.${NORMAL}"
		evaluate_retval
		exit
		fi

		eval $(/usr/local/bin/readhash /var/ipfire/proxy/advanced/settings)
		eval $(/usr/local/bin/readhash /var/ipfire/ethernet/settings)

		if [ -e /var/ipfire/proxy/enable -o -e /var/ipfire/proxy/enable_blue ]; then
			# Add Address to errorpage stylesheet
			sed "s|XXXhostXXX|$GREEN_ADDRESS|g" /var/ipfire/proxy/errorpage-$ERR_DESIGN.css > \
				/etc/squid/errorpage.css

			boot_mesg "Creating Squid swap directories..."
			/usr/sbin/squid -z >/dev/null 2>&1
			evaluate_retval

			# Make sure, that the process above has finished.
			counter=5
			while [ ${counter} -gt 0 ]; do
				if pidofproc -s /usr/sbin/squid; then
					sleep 1
				else
					break
				fi
			done

			boot_mesg "Starting Squid Proxy Server..."
			loadproc /usr/sbin/squid
		fi

		if [ -e /var/ipfire/proxy/transparent ]; then
			transparent $GREEN_DEV
		fi
		if [ -e /var/ipfire/proxy/transparent_blue ]; then
			transparent $BLUE_DEV
		fi
		;;

	stop)
		iptables -t nat -F SQUID

		if [ -e /var/run/squid.pid ]; then
			boot_mesg -n "Stopping Squid Proxy Server (this may take up to a few minutes)..."
			squid -k shutdown >/dev/null 2>&1

			# If some squid processes are still running, wait up to 360 seconds
			# before we go on to kill the remaining process(es) and delete damaged
			# '/var/log/cache/swap.state'.
			n=0
			while squid -k check &>/dev/null && [ $n -lt 360 ]; do
				# Print a dot every 6 seconds
				[ $(( ${n} % 6 )) -eq 0 ] && boot_mesg -n .

				n=$(( ${n} + 1 ))
				sleep 1
			done
			boot_mesg "" # end line

			# If (squid-1) is still running, kill all squid processes
			if squid -k check &>/dev/null || pgrep -fl "(squid-1)" >/dev/null 2>&1; then
				killproc /usr/sbin/squid >/dev/null
				echo_failure

				# Remove damaged journal of cache index
				rm -f /var/log/cache/swap.state

				boot_mesg -n "WARNING: squid could not be gracefully shut down." ${WARNING}
				boot_mesg -n " The cache index was damaged and has been removed."
				boot_mesg -n " The cache data has not been lost and the index will be"
				boot_mesg -n " recreated at the next start."
				boot_mesg "" ${NORMAL}
				echo_warning
			else
				logger -t squid "squid shutdown time: ${n} seconds"

				echo_ok
			fi

			# Kill any redirector processes that might have been left running
			killproc /usr/bin/squidGuard >/dev/null &
			killproc /usr/sbin/updxlrator >/dev/null &
			killproc /usr/bin/squidclamav >/dev/null &
			killproc /usr/sbin/redirect_wrapper >/dev/null &
			wait
		fi

		# Trash remain pid file from squid.
		rm -f /var/run/squid.pid
		;;

	restart)
		$0 stop
		sleep 5
		$0 start
		;;

	reconfigure)
		/usr/sbin/squid -k reconfigure
		;;

	status)
		statusproc /usr/sbin/squid
		statusproc /usr/lib/squid/unlinkd
		;;

	flush)
		$0 stop
		rm -rf /var/log/cache/*
		sleep 1
		$0 start
		;;

	setperms)
		chown -R nobody.squid /var/updatecache/
		;;

	*)
		echo "Usage: $0 {start|stop|restart|status|flush}"
		exit 1
		;;
esac
