#!/bin/bash

# Copyright (C) 2024-2025 Pädagogisches Landesinstitut Rheinland-Pfalz
# Copyright (C) 2024-2025 Daniel Teichmann <daniel.teichmann@das-netzwerkteam.de>

# This script 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 2 of the License, or
# (at your option) any later version.
#
# This script 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, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

COMMON_FILE="/usr/share/debian-edu-router/debian-edu-router.common"
# Load common functions, variables, and logging routines.
if [ -s "${COMMON_FILE}" ]; then
	source "${COMMON_FILE}"
else
	echo "Could not load common file at ${COMMON_FILE}."
	exit 0
fi

export FILTERLISTS_PATH="/var/lib/debian-edu-router/filterlists.d"
if [[ -e "${FILTERLISTS_PATH}/work-in-progress" ]]; then
    if grep -q "BLOCKING_DATE" "${FILTERLISTS_PATH}/work-in-progress" && \
       grep -q "BLOCKING_PID"  "${FILTERLISTS_PATH}/work-in-progress"; then
       source "${FILTERLISTS_PATH}/work-in-progress"
    fi

    file_created_at=""
    pid="unknown PID"
    if [[ -n "${BLOCKING_PID}" ]] && [[ -n "${BLOCKING_DATE}" ]]; then
        file_created_at="$(date -d "${BLOCKING_DATE}" +%s)"
        pid="${BLOCKING_PID}"
    else
        file_created_at="$(date -d "$(stat -c %y "${FILTERLISTS_PATH}"/work-in-progress)" +%s)"
    fi

    now_but_yesterday="$(date -d 'now - 12 hours' +"%s")"

    # If file is older than 12 hours.
    if [[ -z "${file_created_at}" ]] || [ "${now_but_yesterday}" -ge "${file_created_at}" ]; then
        rm -f "${FILTERLISTS_PATH}/work-in-progress"
        warning_log "Program (${pid}) was working for a very long time on filterlists.d/, ignoring found WIP file."
    else
        warning_log "Program (${pid}) is currently working on filterlists.d/ (file found '${FILTERLISTS_PATH}/work-in-progress'), skipping reload of D-E-R Squids."
        exit 0
    fi
fi

squids="$(/usr/bin/systemctl list-dependencies --plain squid_d-e-r.target | tail -n +2 | awk '{ print $1 }')"
if [[ -n "${squids[@]}" ]]; then
	# Now reload all squid_d-e-r@<network> instances.
	echo "${squids}" | xargs /usr/bin/systemctl reload && {
		notice_log "Reloaded all squid_d-e-r@<network> services."
	} || {
		error_log "Failed to reload children of squid_d-e-r.target: ${squids}"
		exit 1
	}
fi
