#!/usr/bin/env bash

set -euo pipefail
export LC_ALL=C

CONFIG_FILE=${BTRFS_SNAPSHOT_CLEAN_CONFIG:-${BTRFS_HELPER_CONFIG:-/etc/sysconfig/btrfs-snapshot-clean.conf}}

log() {
    printf 'btrfs-snapshot-clean: %s\n' "$*" >&2
}

load_config() {
    local line key value
    local have_min_snapshots=0 have_min_age_days=0

    if [[ ! -r $CONFIG_FILE ]]; then
        log "Cannot read config: $CONFIG_FILE"
        return 1
    fi

    while IFS= read -r line || [[ -n $line ]]; do
        [[ $line =~ ^[[:space:]]*(#|$) ]] && continue
        if [[ ! $line =~ ^[[:space:]]*(MIN_SNAPSHOTS|MIN_AGE_DAYS)[[:space:]]*=[[:space:]]*([1-9][0-9]*)[[:space:]]*(#.*)?$ ]]; then
            log "Invalid config line: $line"
            return 1
        fi
        key=${BASH_REMATCH[1]}
        value=${BASH_REMATCH[2]}
        case $key in
            MIN_SNAPSHOTS)
                if (( have_min_snapshots )) || (( ${#value} > 7 )) || (( value > 1000000 )); then
                    log 'MIN_SNAPSHOTS is duplicated or out of range'
                    return 1
                fi
                min_snapshots=$value
                have_min_snapshots=1
                ;;
            MIN_AGE_DAYS)
                if (( have_min_age_days )) || (( ${#value} > 5 )) || (( value > 36500 )); then
                    log 'MIN_AGE_DAYS is duplicated or out of range'
                    return 1
                fi
                min_age_days=$value
                have_min_age_days=1
                ;;
        esac
    done < "$CONFIG_FILE"

    if (( ! have_min_snapshots || ! have_min_age_days )); then
        log 'Config must define MIN_SNAPSHOTS and MIN_AGE_DAYS'
        return 1
    fi
}

list_snapshots() {
    local output line snapshot tags_field description_field prefix mode='' reported_count=-1 list_status=0
    local tag_start=-1 description_start=-1 tag_width=0
    local -a found=()
    local -a on_demand=()
    local -A seen=()

    output=$(timeshift --list --btrfs --scripted) || list_status=$?
    while IFS= read -r line; do
        if [[ $line =~ ^[[:space:]]*Mode[[:space:]]*:[[:space:]]*([A-Z]+) ]]; then
            mode=${BASH_REMATCH[1]}
        elif [[ $line =~ ^[[:space:]]*([0-9]+)[[:space:]]+snapshots?, ]]; then
            reported_count=${BASH_REMATCH[1]}
        elif [[ $line =~ ^[[:space:]]*Num[[:space:]]+Name[[:space:]]+Tags[[:space:]]+Description[[:space:]]*$ ]]; then
            prefix=${line%%Tags*}
            tag_start=${#prefix}
            prefix=${line%%Description*}
            description_start=${#prefix}
            tag_width=$((description_start - tag_start))
        elif [[ $line =~ ^[[:space:]]*[0-9]+[[:space:]]+([>][[:space:]]+)?([0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2})([[:space:]]|$) ]]; then
            snapshot=${BASH_REMATCH[2]}
            if (( tag_start < 0 || tag_width < 5 || ${#line} < description_start )); then
                log 'Cannot locate Timeshift tag column'
                return 1
            fi
            if [[ -n ${seen[$snapshot]+x} ]] || [[ $(date -d "${snapshot:0:10} ${snapshot:11:2}:${snapshot:14:2}:${snapshot:17:2}" '+%Y-%m-%d_%H-%M-%S' 2>/dev/null) != "$snapshot" ]]; then
                log "Invalid or duplicate snapshot in Timeshift list: $snapshot"
                return 1
            fi
            tags_field=${line:tag_start:tag_width}
            description_field=${line:description_start}
            if [[ ! $tags_field =~ ^[[:space:]]*([OBHDWM]([[:space:]]+[OBHDWM])*)?[[:space:]]*$ ]]; then
                log "Invalid Timeshift tags for snapshot: $snapshot"
                return 1
            fi
            seen[$snapshot]=1
            found+=("$snapshot")
            if [[ $tags_field =~ (^|[[:space:]])O([[:space:]]|$) && $description_field =~ ^[[:space:]]*Before\ Offline\ Update[[:space:]]*$ ]]; then
                on_demand+=("$snapshot")
            fi
        fi
    done <<< "$output"

    if [[ $mode != BTRFS ]]; then
        log 'Timeshift did not report BTRFS mode'
        return 1
    fi
    if (( reported_count < 0 )) && [[ $output == *'No snapshots found'* ]] && ((${#found[@]} == 0)); then
        reported_count=0
    fi
    if (( reported_count < 0 || reported_count != ${#found[@]} )); then
        log "Timeshift list count does not match parsed snapshots (${#found[@]}/$reported_count)"
        return 1
    fi
    if (( list_status != 0 && reported_count != 0 )); then
        log "Timeshift list failed with status $list_status"
        return 1
    fi

    ((${#on_demand[@]} == 0)) || printf '%s\n' "${on_demand[@]}"
}

timestamp_epoch() {
    local stamp=$1 parsed
    if [[ ! $stamp =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}$ ]]; then
        log "Invalid timestamp: $stamp"
        return 1
    fi
    parsed=$(date -d "${stamp:0:10} ${stamp:11:2}:${stamp:14:2}:${stamp:17:2}" '+%Y-%m-%d_%H-%M-%S %s') || return 1
    if [[ ${parsed% *} != "$stamp" ]]; then
        log "Invalid timestamp: $stamp"
        return 1
    fi
    printf '%s\n' "${parsed##* }"
}

days_cutoff_epoch() {
    local now=$1 days=$2 now_epoch
    now_epoch=$(timestamp_epoch "$now") || return 1
    printf '%s\n' "$((now_epoch - days * 86400))"
}

select_snapshots_for_deletion() {
    local now=${1:-$(date '+%Y-%m-%d_%H-%M-%S')} listed sorted cutoff snapshot snapshot_time i
    local -a snapshots

    listed=$(list_snapshots) || return 1
    [[ -n $listed ]] || return 0
    sorted=$(printf '%s\n' "$listed" | sort -r) || return 1
    mapfile -t snapshots <<< "$sorted"
    ((${#snapshots[@]} > min_snapshots)) || return 0

    cutoff=$(days_cutoff_epoch "$now" "$min_age_days") || return 1
    for ((i = min_snapshots; i < ${#snapshots[@]}; i++)); do
        snapshot=${snapshots[i]}
        snapshot_time=$(timestamp_epoch "$snapshot") || return 1
        if (( snapshot_time > cutoff )); then
            continue
        fi
        printf '%s\n' "$snapshot"
    done
}

delete_snapshots() {
    local selection=$1 dry_run=${2:-0} snapshot
    local -a snapshots
    if [[ -z $selection ]]; then
        if (( dry_run )); then
            log 'Dry run: no snapshots selected for deletion'
        else
            log 'No snapshots selected for deletion'
        fi
        return 0
    fi
    mapfile -t snapshots <<< "$selection"

    # Validate the full selection before starting any deletion.
    for snapshot in "${snapshots[@]}"; do
        if [[ ! $snapshot =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}$ ]]; then
            log "Invalid snapshot name from selector: $snapshot"
            return 1
        fi
    done

    for snapshot in "${snapshots[@]}"; do
        if (( dry_run )); then
            log "Dry run: would delete snapshot $snapshot"
            continue
        fi
        log "Deleting snapshot $snapshot"
        timeshift --delete --snapshot "$snapshot" --btrfs --scripted --yes || return 1
    done
}

main() {
    local dry_run=0 selection
    if (( $# > 1 )); then
        log 'Invalid arguments'
        return 2
    fi
    case ${1:-} in
        '') ;;
        --dry-run) dry_run=1 ;;
        *) log 'Invalid arguments'; return 2 ;;
    esac

    if (( EUID != 0 )); then
        log 'Timeshift cleanup must run as root'
        return 1
    fi
    if ! type timeshift >/dev/null 2>&1; then
        log 'timeshift is not installed'
        return 1
    fi
    load_config

    selection=$(select_snapshots_for_deletion) || return 1
    delete_snapshots "$selection" "$dry_run"
}

main "$@"
