#!/usr/bin/env bash
# install-screenshot-cleanup-cron.sh — Clear ~/Pictures/Screenshots every 5 minutes.
# Idempotent per-user crontab installer.

set -euo pipefail
IFS=$'\n\t'

readonly SCRIPT_NAME="${0##*/}"
readonly BEGIN_MARKER="# BEGIN managed by install-screenshot-cleanup-cron.sh"
readonly END_MARKER="# END managed by install-screenshot-cleanup-cron.sh"
DRY_RUN=0

usage() {
  cat <<EOF
Usage: $SCRIPT_NAME [--dry-run] [--help]

Installs a per-user cron job that deletes everything inside:

  \$HOME/Pictures/Screenshots

every 5 minutes. The Screenshots directory itself is preserved.

Options:
  --dry-run    Print actions without executing.
  --help, -h   Show this help.
EOF
}

log()  { printf '\033[1;34m[%s]\033[0m %s\n' "${SCRIPT_NAME%.sh}" "$*"; }
die()  { printf '\033[1;31m[%s] ERROR:\033[0m %s\n' "${SCRIPT_NAME%.sh}" "$*" >&2; exit 1; }

while (( $# )); do
  case "$1" in
    --dry-run) DRY_RUN=1 ;;
    -h|--help) usage; exit 0 ;;
    *) die "Unknown argument: $1 (try --help)" ;;
  esac
  shift
done

(( EUID != 0 )) || die "Do not run as root. Run as your normal desktop user so the cron job uses the correct \$HOME."

for tool in crontab awk mktemp mkdir; do
  command -v "$tool" >/dev/null 2>&1 || die "Missing required tool: $tool"
done

SCREENSHOT_DIR="$HOME/Pictures/Screenshots"
CRON_LINE="*/5 * * * * find \"$SCREENSHOT_DIR\" -mindepth 1 -delete"
STAGE="$(mktemp -d -t screenshot-cron.XXXXXX)"
trap 'rm -rf "$STAGE"' EXIT

CURRENT="$STAGE/current"
NEXT="$STAGE/next"
crontab -l >"$CURRENT" 2>/dev/null || true

awk -v begin="$BEGIN_MARKER" -v end="$END_MARKER" '
  $0 == begin { skip = 1; next }
  $0 == end { skip = 0; next }
  skip { next }
  $0 == "# Delete screenshot contents every 5 minutes" { next }
  index($0, "Pictures/Screenshots") && index($0, "-mindepth 1") && index($0, "-delete") { next }
  { print }
' "$CURRENT" >"$NEXT"

{
  printf '%s\n' "$BEGIN_MARKER"
  printf '# Delete screenshot contents every 5 minutes\n'
  printf '%s\n' "$CRON_LINE"
  printf '%s\n' "$END_MARKER"
} >>"$NEXT"

if (( DRY_RUN )); then
  log "Would ensure directory exists: $SCREENSHOT_DIR"
  log "Would install this user crontab:"
  sed 's/^/  /' "$NEXT"
  exit 0
fi

mkdir -p "$SCREENSHOT_DIR"
crontab "$NEXT"

log "Installed screenshot cleanup cron job:"
printf '  %s\n' "$CRON_LINE"
log "Done."
