#!/usr/bin/env bash
# backup-menu — interactive resticprofile menu

set -euo pipefail

PROFILES=(dotfiles projects vaults files pictures)
STATE_FILE="${XDG_STATE_HOME:-$HOME/.local/state}/backup-last-run"

_profile_label() {
    local profile=$1
    local last
    last=$(resticprofile -n "$profile" snapshots --json 2>/dev/null \
        | python3 -c "
import sys, json
try:
    snaps = json.load(sys.stdin)
    if snaps:
        t = snaps[-1]['time'][:16].replace('T', ' ')
        print(f'last: {t}')
    else:
        print('no snapshots')
except:
    print('?')
" 2>/dev/null || echo "?")
    printf "%-16s  %s" "$profile" "$last"
}

_run_backup() {
    local profile=$1
    echo "▶ resticprofile -n $profile backup"
    resticprofile -n "$profile" backup
    mkdir -p "$(dirname "$STATE_FILE")"
    date +%s > "$STATE_FILE"
}

_run_forget() {
    local profile=$1
    echo "▶ resticprofile -n $profile forget"
    resticprofile -n "$profile" forget
}

_show_snapshots() {
    local profile=$1
    resticprofile -n "$profile" snapshots 2>&1 | less
}

_run_all() {
    for p in "${PROFILES[@]}"; do
        _run_backup "$p"
    done
}

main() {
    if [[ "${1:-}" == "--all" ]]; then
        _run_all
        return
    fi

    if ! command -v fzf &>/dev/null; then
        echo "fzf not found"
        exit 1
    fi

    local lines=()
    for p in "${PROFILES[@]}"; do
        lines+=("$(_profile_label "$p")")
    done

    local selected
    selected=$(printf '%s\n' "${lines[@]}" | fzf \
        --prompt "backup > " \
        --header "Enter — запустить бэкап | Ctrl-F — forget | Ctrl-S — снапшоты" \
        --bind "ctrl-f:become(echo '__forget__'$(echo {} | awk '{print $1}'))" \
        --bind "ctrl-s:become(echo '__snaps__'$(echo {} | awk '{print $1}'))" \
        --no-sort) || exit 0

    local profile
    profile=$(echo "$selected" | awk '{print $1}')

    case "$selected" in
        __forget__*) _run_forget "${selected#__forget__}" ;;
        __snaps__*)  _show_snapshots "${selected#__snaps__}" ;;
        *)           _run_backup "$profile" ;;
    esac
}

main "$@"
