#!/bin/sh

set -eu

. /etc/dnsmasq-blocklists/blocklists.conf

mkdir -p "$TARGET_DIR"
mkdir -p "$WORK_DIR"

RAW_DIR="$WORK_DIR/raw"
TMP_COMBINED="$WORK_DIR/blocklist.tmp"
TMP_GZ="$WORK_DIR/blocklist.conf.gz.tmp"
FINAL_GZ="$TARGET_DIR/blocklist.conf.gz"

mkdir -p "$RAW_DIR"

any_failed=0

download_file() {
  name="$1"
  url="$2"

  target_file="$RAW_DIR/$name.list"

  attempt=1
  delay="$SLEEP_BASE"

  while [ "$attempt" -le "$RETRIES" ]; do

    rm -f "$target_file"

    wget -q \
      --timeout="$WGET_TIMEOUT" \
      -O "$target_file" \
      "$url" && status=0 || status=1

    if [ "$status" -eq 0 ] && [ -s "$target_file" ]; then
      echo "OK: $url"
      return 0
    fi

    echo "FAIL attempt $attempt: $url"

    rm -f "$target_file"

    sleep "$delay"

    delay=$((delay * 2))
    [ "$delay" -gt "$SLEEP_MAX" ] && delay="$SLEEP_MAX"

    attempt=$((attempt + 1))
  done

  return 1
}

download_group() {
  list="$1"

  echo "$list" | while IFS= read -r entry; do
    [ -z "$entry" ] && continue

    name="${entry%%|*}"
    url="${entry#*|}"

    if ! download_file "$name" "$url"; then
      echo "$name $url failed"
      any_failed=1
    fi
  done
}

exec 200>"$LOCK_FILE"
flock -n 200 || exit 0

download_group "$DNSMASQ_LISTS"
download_group "$DOMAIN_LISTS"
download_group "$HOSTS_LISTS"

if [ "$any_failed" -eq 1 ]; then

  wget -q -O- \
    --post-data="One or more dnsmasq blocklists failed." \
    --header="Authorization: Bearer $NTFY_EVLAB_TOKEN" \
    --header="Title: dnsmasq Blocklist Update Failed" \
    --header="Tags: red_circle" \
    --header="Priority: 5" \
    "$NTFY_HOST/$NTFY_TOPIC" >/dev/null

  exit 1
fi

find "$RAW_DIR" -type f -print0 \
| xargs -0 cat \
| grep -Ev '^\s*($|#)' \
| sed -E '
s@^(0\.0\.0\.0|127\.0\.0\.1)[[:space:]]+([^[:space:]]+).*$@address=/\2/#@
t

s@^(address|server|local)=/([^/]+)/.*$@address=/\2/#@
t

s@^([a-zA-Z0-9._-]+)$@address=/\1/#@
' \
| tr '[:upper:]' '[:lower:]' \
| sed 's/\.$//' \
| grep '^address=/[^/=][^ ]*/#$' \
| sort -u \
| gzip -9 \
> "$TMP_GZ"

gzip -t "$TMP_GZ"

mv -f "$TMP_GZ" "$FINAL_GZ"

echo "Generated $FINAL_GZ"

rc-service dnsmasq restart

echo "dnsmasq restarted"
