#!/bin/bash

# Copyright (C) 2024 Pädagogisches Landesinstitut Rheinland-Pfalz
# Copyright (C) 2024 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.

# A notice will always be shown but should not be highlighted as much (as errors/warnings).
function notice_log() {
	echo -e "${blue}$(printf "%-9s" "NOTICE: ")${bold}$@${normal}"
}

export FILTERLISTS_PATH="/var/lib/debian-edu-router/filterlists.d/"
if [[ -e "${FILTERLISTS_PATH}/work-in-progress" ]]; then
    # || true -> date may fail to parse text.
    file_created_at="$(date -d "$(cat ${FILTERLISTS_PATH}/work-in-progress | tr -d '\n')" +%s)"
    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"
        notice_log "A script was working for a very long time on filterlists.d/, ignoring found WIP file."
    else
        notice_log "A script 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 }')"

# Now reload all squid_d-e-r@<network> instances.
echo "${squids}" | xargs /usr/bin/systemctl reload
