#!/bin/bash
# gravity-validate.sh — pre-start integrity check for Pi-hole's gravity.db
#
# Runs as the container entrypoint. If gravity.db is empty or has an invalid
# SQLite header (the symptom of the /dev/shm corruption outage), move it aside
# so Pi-hole regenerates a clean DB on start instead of crashing.
set -e
GRAVITY_DB="/etc/pihole/gravity.db"
TIMESTAMP=$(date +%Y%m%d%H%M%S)

if [ -f "$GRAVITY_DB" ]; then
    if [ ! -s "$GRAVITY_DB" ]; then
        echo "[gravity-validate] gravity.db is empty, moving aside"
        mv "$GRAVITY_DB" "${GRAVITY_DB}.corrupt.${TIMESTAMP}"
    else
        HEADER=$(head -c 15 "$GRAVITY_DB" 2>/dev/null || true)
        if [ "$HEADER" != "SQLite format 3" ]; then
            echo "[gravity-validate] gravity.db invalid header, moving aside"
            mv "$GRAVITY_DB" "${GRAVITY_DB}.corrupt.${TIMESTAMP}"
        fi
    fi
fi
# Keep only the 3 most recent corrupt backups (names carry a timestamp,
# so lexical reverse-sort = newest-first).
find /etc/pihole -maxdepth 1 -name 'gravity.db.corrupt.*' -print 2>/dev/null \
  | sort -r | tail -n +4 | xargs -r rm -f
echo "[gravity-validate] OK, starting Pi-hole"
exec /usr/bin/start.sh "$@"
