#!/usr/bin/env bash
#
# review-delete.sh
# Finds files whose modification time falls within one specific minute
# (default: 2026-11-27 19:53, i.e. 19:53:00 through 19:53:59) and asks
# yes/no for each one before deleting it.
#
# Usage (any of these work):
#   ./review-delete.sh "2026-11-27 19:53" /path/to/public_html
#   ./review-delete.sh 2026-11-27 19:53 /path/to/public_html
#   ./review-delete.sh "2026-11-27 19:53:20" /path/to/public_html   (one exact second)
#
# Times are in the server's local timezone (the same one `ls -l` and
# `stat` show). Check yours with: date
#
# Option (environment variable):
#   TIMETYPE=c       match the inode change time (ctime) instead of the
#                    modification time (mtime). ctime can't be faked with
#                    `touch`, so it is the better one if you suspect the
#                    attacker reset timestamps.

set -u

TIMETYPE="${TIMETYPE:-m}"

# The time can be given quoted ("2026-11-27 19:53") or as two separate words
# (2026-11-27 19:53), with an optional T between date and time, and with
# optional seconds (19:53:20).
if [[ "${1:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] && [[ "${2:-}" =~ ^[0-9]{2}:[0-9]{2}(:[0-9]{2})?$ ]]; then
  STAMP="$1 $2"
  TARGET="${3:-.}"
else
  STAMP="${1:-2026-11-27 19:53}"
  TARGET="${2:-.}"
fi
STAMP="${STAMP/T/ }"

if [[ "$STAMP" =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2})\ ([0-9]{2}:[0-9]{2})(:([0-9]{2}))?$ ]]; then
  DAY="${BASH_REMATCH[1]}"
  HM="${BASH_REMATCH[2]}"
  SECS="${BASH_REMATCH[4]}"
else
  echo "Could not understand the time: '$STAMP'" >&2
  echo "Use a form like:  ./review-delete.sh \"2026-11-27 19:53\" /path/to/dir" >&2
  echo "              or:  ./review-delete.sh 2026-11-27 19:53 /path/to/dir" >&2
  exit 1
fi

if [ -n "$SECS" ]; then
  START="$DAY $HM:$SECS"; WIDTH=1      # one exact second
else
  START="$DAY $HM:00";    WIDTH=60     # the whole minute
fi

if ! START_EPOCH="$(date -d "$START" +%s 2>/dev/null)"; then
  echo "Could not parse that date/time: '$START' (is the date real?)" >&2
  exit 1
fi
# find's -newer tests are strictly "later than", so the window is built from
# the last instant before the period and the last instant inside it.
LOW="$(date -d "@$((START_EPOCH - 1))" '+%Y-%m-%d %H:%M:%S').999999999"
HIGH="$(date -d "@$((START_EPOCH + WIDTH - 1))" '+%Y-%m-%d %H:%M:%S').999999999"

case "$TIMETYPE" in
  m) NEWER="-newermt"; LABEL="modified" ;;
  c) NEWER="-newerct"; LABEL="changed (ctime)" ;;
  *) echo "TIMETYPE must be m or c." >&2; exit 1 ;;
esac

if [ ! -d "$TARGET" ]; then
  echo "Directory not found: $TARGET" >&2
  exit 1
fi

if [ ! -r /dev/tty ]; then
  echo "This script needs an interactive terminal." >&2
  exit 1
fi

TARGET="$(cd "$TARGET" && pwd)"
SELF="$(readlink -f "$0")"

deleted=0
skipped=0
failed=0
quit=0

echo "Scanning $TARGET for files $LABEL between $START and ${HIGH%.*} ..."
echo

# NUL-delimited so filenames with spaces or newlines are handled safely.
# Fields: modified time, owner, size in bytes, path (tab separated).
while IFS= read -r -d '' record <&3; do
  date="${record%%$'\t'*}";  rest="${record#*$'\t'}"
  owner="${rest%%$'\t'*}";   rest="${rest#*$'\t'}"
  size="${rest%%$'\t'*}";    path="${rest#*$'\t'}"

  # Never touch this script itself.
  [ "$(readlink -f "$path")" = "$SELF" ] && continue

  while true; do
    echo "----------------------------------------"
    echo "File:     $path"
    echo "Modified: $date   Owner: $owner   Size: ${size} bytes"
    read -r -p "Delete this file? [y]es / [n]o / [v]iew / [q]uit: " answer </dev/tty
    case "${answer,,}" in
      y|yes)
        if rm -f -- "$path"; then
          echo "  Deleted."
          deleted=$((deleted + 1))
        else
          echo "  Delete failed (permissions?)."
          failed=$((failed + 1))
        fi
        break
        ;;
      n|no|"")
        echo "  Skipped."
        skipped=$((skipped + 1))
        break
        ;;
      v|view)
        echo "  --- first 1000 bytes (non-printable characters escaped) ---"
        head -c 1000 -- "$path" | cat -v
        echo
        echo "  --- end of preview ---"
        ;;
      q|quit)
        quit=1
        break
        ;;
      *)
        echo "  Please answer y, n, v or q."
        ;;
    esac
  done

  [ "$quit" -eq 1 ] && break
done 3< <(
  find "$TARGET" -type f "$NEWER" "$LOW" ! "$NEWER" "$HIGH" \
    -printf '%TY-%Tm-%Td %TH:%TM:%TS\t%u\t%s\t%p\0' | sort -z
)

echo
echo "========================================"
echo "Deleted: $deleted   Skipped: $skipped   Failed: $failed"
[ "$quit" -eq 1 ] && echo "(Stopped early; remaining files were not reviewed.)"
