#!/bin/bash
# Backup Auto-Heal: frees space when backup drive gets full
# Runs as cron, NTFS-safe
set -eo pipefail

MOUNT="/media/rogeryu/TYH-BACKUP"
BASE="$MOUNT/btrfs-backup"
LOCK="/var/lock/btrfs-autoheal.lock"
LOG="/home/rogeryu/btrfs_backup_autoheal.log"
MIN_GB=100
TARGET_GB=150
TOKEN="863167…Kt0E"
CHAT="8325862820"

# Lock
exec 200>"$LOCK" || exit 1
flock -n 200 || exit 0
trap "rm -f $LOCK" EXIT

# Check mount
mountpoint -q "$MOUNT" || { echo "$(date) Drive not mounted" >> "$LOG"; exit 0; }

# Check usage
avail_kb=$(df --output=avail "$MOUNT" | tail -1)
avail_gb=$((avail_kb / 1048576))
total_kb=$(df --output=size "$MOUNT" | tail -1)
total_gb=$((total_kb / 1048576))
used_gb=$((total_gb - avail_gb))
used_pct=$((used_gb * 100 / total_gb))
echo "$(date) Disk: ${used_gb}G/${total_gb}G (${used_pct}%), ${avail_gb}G free" >> "$LOG"

# Check if last backup failed
failed=0
last_line=$(grep -a -E 'WITH ERRORS|FATAL' /home/rogeryu/btrfs_backup.log 2>/dev/null | tail -1)
[ -n "$last_line" ] && failed=1 && echo "$(date) Last backup failed: $last_line" >> "$LOG"

# Only act if disk is full or backup failed
[ "$avail_gb" -ge "$MIN_GB" ] && [ "$failed" = "0" ] && exit 0

# Notify
msg="⚠️ *Auto-Heal* — Backup drive ${used_pct}% full (${avail_gb}G free)."
curl -s -X POST "https://api.telegram.org/bot${TOKEN}/sendMessage" \
  -d "chat_id=$CHAT" -d "text=$msg" -d "parse_mode=Markdown" >/dev/null 2>&1 || true

# === Prune old snapshots ===
# Sort ascending (oldest first). Keep the NEWEST one. Delete the rest.
snaps=($(find "$BASE" -maxdepth 1 -type d -name '????-??-??_*' 2>/dev/null | sort))
count=${#snaps[@]}

if [ "$count" -le 1 ]; then
    echo "$(date) Only $count snapshot(s) — keeping all." >> "$LOG"
else
    newest="${snaps[$((count - 1))]}"
    newest_name=$(basename "$newest")
    echo "$(date) Keeping newest: $newest_name. Pruning the rest..." >> "$LOG"

    deleted=0
    for ((i=0; i<count-1; i++)); do
        snap="${snaps[$i]}"
        name=$(basename "$snap")

        # Safety: never delete the newest snapshot
        [ "$snap" = "$newest" ] && { echo "$(date) SAFETY: skipping newest $name" >> "$LOG"; continue; }

        echo "$(date) Removing $name ..." >> "$LOG"
        # NTFS-safe: find -depth handles deep dirs that rm -rf chokes on
        find "$snap" -depth ! -name . -delete 2>/dev/null || \
            (find "$snap" -type f -delete 2>/dev/null; find "$snap" -depth -type d -empty -delete 2>/dev/null) || \
            rm -rf "$snap" 2>/dev/null || \
            echo "$(date) WARN: could not delete $name" >> "$LOG"
        deleted=$((deleted + 1))

        # Stop early if enough free (when backup hasn't failed)
        if [ "$failed" = "0" ]; then
            now_kb=$(df --output=avail "$MOUNT" | tail -1)
            now_gb=$((now_kb / 1048576))
            [ "$now_gb" -ge "$TARGET_GB" ] && break
        fi
    done
fi

# Clean _old and Trash
[ -d "$BASE/_old" ] && find "$BASE/_old" -depth ! -name . -delete 2>/dev/null || true
[ -d "$BASE/../.Trash-1000/files" ] && rm -rf "$BASE/../.Trash-1000/files/"* "$BASE/../.Trash-1000/info/"* 2>/dev/null || true

# Report
final_gb=$(df -h --output=avail "$MOUNT" | tail -1 | tr -d ' ')
echo "$(date) Cleanup done: removed $deleted snapshots. Free: $final_gb" >> "$LOG"
[ "$deleted" -gt 0 ] && \
  curl -s -X POST "https://api.telegram.org/bot${TOKEN}/sendMessage" \
    -d "chat_id=$CHAT" -d "text=✅ *Auto-Heal* — Removed $deleted old snapshots. ${final_gb} free." \
    -d "parse_mode=Markdown" >/dev/null 2>&1 || true
