you-dont-need-pihole/update.sh
2022-12-15 11:54:02 -06:00

113 lines
2.7 KiB
Bash
Executable file

#!/bin/bash
# vi: et sts=4 sw=4 ts=4
###############################################################################
# You Don't Need Pi-hole
# Network-wide DNS blocking without extra hardware.
#
# Project URL: https://codeberg.org/h3xx/you-dont-need-pihole
#
# License GPLv3: GNU GPL version 3.0 (https://www.gnu.org/licenses/gpl-3.0.html)
# with Commons Clause 1.0 (https://commonsclause.com/).
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
# You may NOT use this software for commercial purposes.
###############################################################################
set -e
WORKDIR=${0%/*}
CFG=$WORKDIR/update.cfg
# Config defaults
BACKUPSUFFIX=
BLOCKLIST=$WORKDIR/block.list
LIST_DIR=$WORKDIR/lists
OUT=()
URL=()
DNSMASQ_RESTART_COMMAND=()
if [[ -f $CFG ]]; then
. "$CFG"
fi
TEMP_DIR=$(mktemp -d -t "${0##*/}.XXXXXX")
cleanup() {
rm -fr -- "$TEMP_DIR"
}
trap 'cleanup' EXIT
copy_perms() {
local -r FROM=$1 TO=$2
chmod --reference="$FROM" -- "$TO"
if [[ $UID -eq 0 ]]; then
chown --reference="$FROM" -- "$TO"
fi
}
replace_with() {
local -r ORIG=$1 NEW=$2
if ! diff -q -- "$ORIG" "$NEW" &>/dev/null; then
# There's a change
if [[ -f $ORIG ]]; then
copy_perms "$ORIG" "$NEW"
if [[ -n $BACKUPSUFFIX ]]; then
mv -- "$ORIG" "$ORIG$BACKUPSUFFIX"
fi
else
mkdir -p -- "${ORIG%/*}"
fi
mv -- "$NEW" "$ORIG"
else
printf 'File "%s" not modified\n' \
"$ORIG" \
>&2
fi
}
(cd "$WORKDIR" &&
git submodule update --init 'repos-noupdates/*' &&
git submodule update --init --remote 'repos/*'
)
for (( I = 0 ; I < ${#OUT[@]} ; ++I )); do
MY_URL=${URL[$I]}
MY_OUT=${OUT[$I]}
if [[ -z $MY_URL ]]; then
echo "$CFG: URL[$I] empty" >&2
exit 2
fi
if [[ -z $MY_OUT ]]; then
echo "$CFG: OUT[$I] empty" >&2
exit 2
fi
TEMP_OUT=$(mktemp -p "$TEMP_DIR")
wget \
-O "$TEMP_OUT" \
"$MY_URL"
replace_with "$MY_OUT" "$TEMP_OUT"
done
TEMP_BLOCKLIST=$(mktemp -p "$TEMP_DIR")
"$WORKDIR/make-block.pl" --out="$TEMP_BLOCKLIST"
# Blocklist generation succeeded, install it!
if [[ ! -e $BLOCKLIST ]]; then
(
# First time:
# Create an empty blocklist with -rw-r--r-- permissions.
# Prevents file not being readable; disregard permissions coming from
# whatever file permissions 'mktemp' sets.
umask 0022
touch -- "$BLOCKLIST"
)
fi
replace_with "$BLOCKLIST" "$TEMP_BLOCKLIST"
if [[ ${#DNSMASQ_RESTART_COMMAND[@]} -gt 0 ]]; then
"${DNSMASQ_RESTART_COMMAND[@]}"
fi