#!/bin/bash
source /home/insuraz1/public_html/_bildr/backup/gdrive.sh

# Check args
if [ -z "$1" ] || [ -z "$2" ]; then
    echo "Usage: $0 <domain> <search-term>"
    exit 1
fi

prefix="/home/insuraz1/public_html"
surffix="bildr/media/backups"

# Build directory path safely
dir="$prefix/$1/$surffix"

if [ ! -d "$dir" ]; then
    echo "Directory not found: $dir"
    exit 1
fi

# Search ONLY files that contain $2 exactly (segment or whole word)
# Avoid matching Jessica, Jess.Connolly, JessSomething
backup=$(grep -Erl -- "/$2(/|$)" "$dir" | xargs ls -t 2>/dev/null | head -n 1)

if [ -n "$backup" ]; then
    refresh_access_token
    get_account_info
    gdrive_roll_back "$backup" "$2"
else
    echo "No matching backups found in: $dir"
fi
