you-dont-need-pihole/update.sh
2023-07-11 12:55:25 -05:00

109 lines
2.7 KiB
Bash
Executable file

#!/bin/bash
###############################################################################
# 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.
###############################################################################
WORKDIR=${0%/*}
CFG=$WORKDIR/update.cfg
# Config defaults
BACKUPSUFFIX=
BLOCKLIST=$WORKDIR/block.list
OUT=()
URL=()
DNSMASQ_RESTART_COMMAND=()
if [[ -f $CFG ]]; then
. "$CFG" || exit
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" || exit
if [[ $UID -eq 0 ]]; then
chown --reference="$FROM" -- "$TO" || exit
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" || exit
fi
else
mkdir -p -- "${ORIG%/*}" || exit
fi
mv -- "$NEW" "$ORIG" || exit
else
printf 'File "%s" not modified\n' \
"$ORIG" \
>&2
fi
}
(cd "$WORKDIR" &&
git submodule update --init 'repos-noupdates/*' &&
git submodule update --init --remote 'repos/*'
) || exit
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" || exit
replace_with "$MY_OUT" "$TEMP_OUT"
done
TEMP_BLOCKLIST=$(mktemp -p "$TEMP_DIR")
"$WORKDIR/make-block.pl" --out="$TEMP_BLOCKLIST" || exit
# 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"
) || exit
fi
replace_with "$BLOCKLIST" "$TEMP_BLOCKLIST"
if [[ ${#DNSMASQ_RESTART_COMMAND[@]} -gt 0 ]]; then
"${DNSMASQ_RESTART_COMMAND[@]}" || exit
fi