#!/usr/bin/env bash

##
# btrfs-auto-snapshot for Linux
# Automatically create, rotate, and destroy periodic BTRFS snapshots.
# Copyright 2014-2026 Doug Hunley <doug.hunley@gmail.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307  USA

set -euo pipefail

#set -o functrace
#set -o xtrace

BTRFS_AUTO_SNAPSHOT_VERSION=v2.1.1

# Define various error codes
ERR_SUCCESS=0
ERR_STDIN_EMPTY=1
ERR_MISSING_SYS_REQS=2
ERR_GETOPT_FAILED=128
ERR_KEEP_NEGATIVE=129
ERR_PREFIX_WRONG=130
ERR_FS_MISSING=133
ERR_FS_SLASHIES=134
ERR_FS_NO_BTRFS=135

trap argsp_cmdline_exit_handler SIGUSR1

# set defaults
DEF_SNAPS_DIR='.btrfs'

argsp_cmdline_exit="${ERR_SUCCESS}"
debug=''
dry_run=''
keep=''
label=''
prefix='btrfs-auto-snap'
quiet=''
use_syslog=''
verbose=''
writeable='-r'

##
# Check for available necessary system requirements, like a current enough bash and stuff.
#
check_sys_reqs()
{
    unset assoc
    # shellcheck disable=SC2034
    if ! declare -A assoc 2>/dev/null; then
        echo "Associative arrays not supported! At least BASH 4 needed."
        exit ${ERR_MISSING_SYS_REQS}
    fi
}

usage()
{
    echo "$0 $BTRFS_AUTO_SNAPSHOT_VERSION"
    echo
    echo "Usage: $0 [options] [-l label] <'//' | name [name...]>
    -d, --debug         Print debugging messages
    -g, --syslog        Write to syslog
    -h, --help          Print this usage message
    -k, --keep=NUM      Keep NUM recent snapshots and destroy older snapshots
    -l, --label=LAB     LAB is usually 'hourly', 'daily', or 'monthly'
    -n, --dry-run       Print actions w/o actually doing
    -p, --prefix=PRE    PRE is 'btrfs-auto-snap' by default
    -q, --quiet         Suppress warning and notices on STDOUT
    -v, --verbose       Print info messages
    -w, --writeable     Create writeable snapshots instead of read-only
    name                File system name(s), or '//' for all file systems
"
}

log()
{
    LEVEL=$1
    shift 1

    case $LEVEL in
         eme*)
            test -n "$use_syslog" && logger -t "$prefix" -p daemon.emerge -- "$*"
            echo Emergency: "$*" 1>&2
            ;;
         ale*)
            test -n "$use_syslog" && logger -t "$prefix" -p daemon.alert -- "$*"
            echo Alert: "$*" 1>&2
            ;;
         cri*)
            test -n "$use_syslog" && logger -t "$prefix" -p daemon.crit -- "$*"
            echo Critical: "$*" 1>&2
            ;;
         err*)
            test -n "$use_syslog" && logger -t "$prefix" -p daemon.err -- "$*"
            echo Error: "$*" 1>&2
            ;;
         war*)
            test -n "$use_syslog" && logger -t "$prefix" -p daemon.warn -- "$*"
            echo Warning: "$*" 1>&2
            ;;
         not*)
            test -n "$use_syslog" && logger -t "$prefix" -p daemon.notice -- "$*"
            test -n "$verbose" && echo Notice: "$*" 1>&2
            ;;
         inf*)
            test -n "$verbose" && echo "$*"
            ;;
         deb*)
            test -n "$debug" && echo Debug: "$*"
            ;;
         *)
            test -n "$use_syslog" && logger -t "$prefix" -- "$*"
            echo "$*" 1>&2
            ;;
    esac

    return 0
}

##
# {@code STDIN} can only be consumed once, so read and return it here for later processing.
#
# The current approach is to have one argument per line, so we are iterating all of those
# already, remove empty lines, comments etc. and are able to check if anything was read at
# all in the end. If not, this is most likely an error, as it doesn't make much sense to
# explicitly call us, so the script is aborted.
#
# @return {@code [0]="..." [1]="..." [...]}
# @see <a href="https://stackoverflow.com/a/16843375/2055163">How to return an array in
# bash without using globals?</a>
##
argsp_stdin_to_array()
{
    local -a ret_val=()
    local line

    while IFS= read -r line; do
        # Trim leading/trailing whitespace
        line="${line#"${line%%[![:space:]]*}"}"
        line="${line%"${line##*[![:space:]]}"}"

        # Skip empty lines and comments
        [[ -z "${line}" || "${line}" == \#* ]] && continue

        # shellcheck disable=SC2190
        ret_val+=("${line}")
    done < /dev/stdin

    if [ ${#ret_val[@]} -eq 0 ]; then
        echo 'No arguments given using STDIN.' >&2
        exit "${ERR_STDIN_EMPTY}"
    fi

    declare -p ret_val | sed -e 's/^declare -a [^=]*=//'
}

##
# Parse and set command line arguments, possibly aborting in case of errors or missing
# paths to actually work with.
#
# @param[in] Callers need to forward {@code $@}!
# return     Associative array with all options and parsed paths.
##
argsp_cmdline()
{
    declare -A ret_val

    ret_val[debug]=''
    ret_val[dry_run]=''
    ret_val[keep]=''
    ret_val[label]='adhoc'
    ret_val[prefix]='btrfs-auto-snap'
    ret_val[use_syslog]=''
    ret_val[verbose]=''
    ret_val[quiet]=''
    ret_val[writeable]='-r'
    ret_val[paths]=''
    ret_val[help]='0'

    while [ $# -gt 0 ]; do
        case "$1" in
             -d | --debug)
                ret_val[debug]=1
                ret_val[quiet]=''
                ret_val[verbose]=1
                shift 1
            ;;
             -g | --syslog)
                ret_val[use_syslog]=1
                shift 1
            ;;
             -h | --help)
                ret_val[help]=1
                shift 1
            ;;
             -k | --keep)
                if [[ ! "$2" =~ ^[0-9]+$ ]] || [ "$2" -le 0 ]; then
                    log error "The $1 parameter must be a positive integer."
                    argsp_cmdline_exit="${ERR_KEEP_NEGATIVE}"
                    kill -SIGUSR1 $$
                fi

                ret_val[keep]="$2"
                shift 2
            ;;
             -l | --label)
                if [[ "$2" =~ [^[:alnum:]_.:\ -] ]]; then
                    log error "The $1 parameter must be alphanumeric."
                    argsp_cmdline_exit="${ERR_PREFIX_WRONG}"
                    kill -SIGUSR1 $$
                fi

                ret_val[label]="$2"
                shift 2
            ;;
             -n | --dry-run)
                ret_val[dry_run]='echo'
                ret_val[verbose]=1
                log info "Doing a dry run. Not running these commands..."
                shift 1
            ;;
             -p | --prefix)
                if [[ "$2" =~ [^[:alnum:]_.:\ -] ]]; then
                    log error "The $1 parameter must be alphanumeric."
                    argsp_cmdline_exit="${ERR_PREFIX_WRONG}"
                    kill -SIGUSR1 $$
                fi

                ret_val[prefix]="$2"
                shift 2
            ;;
             -q | --quiet)
                ret_val[debug]=''
                ret_val[quiet]=1
                ret_val[verbose]=''
                shift 1
            ;;
             -v | --verbose)
                ret_val[quiet]=''
                ret_val[verbose]=1
                shift 1
            ;;
             -w | --writeable)
                ret_val[writeable]=''
                shift 1
            ;;
             --)
                shift 1
                break
            ;;
             *)
                break
            ;;
        esac
    done

    if [ $# -eq 0 ]; then
        if [ "${ret_val[help]}" -eq 0 ]; then
            log error "The file system argument list is empty."
            log error "Please see $0 --help."
            argsp_cmdline_exit="${ERR_FS_MISSING}"
            kill -SIGUSR1 $$
        fi
    fi

    # Count the number of times '//' appears on the command line.
    local slashies=0
    for i in "$@"; do
         test "$i" = '//' && slashies=$((slashies + 1))
    done

    if [ $# -gt 1 ] && [ $slashies -gt 0 ]; then
        log error "The // must be the only argument if it is given."
        argsp_cmdline_exit="${ERR_FS_SLASHIES}"
        kill -SIGUSR1 $$
    fi

    ret_val[paths]="$*"
    declare -p ret_val | sed -e 's/^declare -A [^=]*=//'
}

##
# Exit with the code stored in {@code argsp_cmdline_exit}.
#
# The corresponding parser function needs to be called as a subshell to be able to process
# the returned list of paths to work with. So exit within that function doesn't work
# easily, which is worked around by using a special global variable and {@code kill} with
# {@code trap}.
##
argsp_cmdline_exit_handler()
{
    exit ${argsp_cmdline_exit}
}

##
# Calculate the BTRFS-mountpoints to start looking at things from.
#
# The important thing to note is that BTRFS layouts can be VERY different: Some systems use
# multiple mountpoints for multiple subvolumes, some use only one mountpoint, because all
# the subvolumes of interest are children of that path already, the names of subvolumes in
# BTRFS might be different from the path they are mounted too etc. Though, it's totally OK
# to mix mounted and unmounted subvolumes, while at some point we need to distinguish them.
# This is done by storing the mountpoints, which we assume to always be subvolumes, else
# individual mountpoints don't make too much sense, and their corresponding subvolume path.
# When retrieving all subvolumes of all mountpoints, this allows removing already known
# child subvolumes which are mountpoints on their own already and processed as such.
#
# The following are some examples of possible mountpoints:
#
# {@code /dev/sda2 / btrfs rw,noatime,nodiratime,compress=zlib:3,ssd,space_cache,subvolid=5,subvol=/ 0 0}
# {@code /dev/sda2 / btrfs rw,relatime,space_cache,subvolid=256,subvol=/@ 0 0}
# {@code /dev/sda2 /boot/grub2/i386-pc btrfs rw,relatime,space_cache,subvolid=266,subvol=/@/boot/grub2/i386-pc 0 0}
# {@code /dev/sda2 /boot/grub2/x86_64-efi btrfs rw,relatime,space_cache,subvolid=265,subvol=/@/boot/grub2/x86_64-efi 0 0}
# {@code /dev/sda2 /home btrfs rw,relatime,space_cache,subvolid=264,subvol=/@/home 0 0}
# {@code /dev/sda2 /opt btrfs rw,relatime,space_cache,subvolid=263,subvol=/@/opt 0 0}
# {@code /dev/sda2 /root btrfs rw,relatime,space_cache,subvolid=262,subvol=/@/root 0 0}
# {@code /dev/sda2 /tmp btrfs rw,relatime,space_cache,subvolid=260,subvol=/@/tmp 0 0}
# {@code /dev/sda2 /srv btrfs rw,relatime,space_cache,subvolid=261,subvol=/@/srv 0 0}
# {@code /dev/sda2 /usr/local btrfs rw,relatime,space_cache,subvolid=259,subvol=/@/usr/local 0 0}
# {@code /dev/sda2 /var btrfs rw,relatime,space_cache,subvolid=258,subvol=/@/var 0 0}
#
# @return Associative array mapping mountpoints and their subvolumes.
#
btrfs_mounts_calc()
{
    local -A ret_val
    local line

    while read -r line; do
        [[ "${line}" != *btrfs* ]] && continue

        local -a parts
        read -ra parts <<< "${line}"
        local path="${parts[1]}"
        local opts="${parts[3]}"
        local subvol="/"

        if [[ "${opts}" =~ subvol=([^,]+) ]]; then
            subvol="${BASH_REMATCH[1]}"
        fi

        # Normalize subvol: remove leading slash for consistency with list output
        subvol="${subvol#/}"

        ret_val["${path}"]="${subvol}"
    done < /proc/mounts

    declare -p ret_val | sed -e 's/^declare -A [^=]*=//'
}

##
# Calculate all BTRFS subvolumes based on all mounted BTRFS file systems.
#
# "zfs-auto-snapshot" is not only able to snapshot all pools, but as well all individual
# datasets when using "//" as path. This function actually allows the same approach by not
# only looking at mountpounts for BTRFS file systems, but their contained subvolumes as
# well. By default, each and every subvolume simply gets a ".btrfs" directory to take
# snapshots and snapshots themself are of course excluded here.
#
# @stdin  Associative array mapping mountpoints and their subvolumes
# @return All subvolumes, one per line.
#
btrfs_subvols_calc()
{
    local -a ret_val=()
    local mp
    eval "declare -A mps=$(cat /dev/stdin)"

    for mp in "${!mps[@]}"; do
        local mp_subvol="${mps[${mp}]}"
        # shellcheck disable=SC2190
        ret_val+=("${mp}")

        local subvol
        # Get relative paths of all subvolumes under this mountpoint
        while read -r subvol; do
            [[ -z "${subvol}" ]] && continue

            local abs_path
            local mp_norm="${mp%/}"

            # Map subvolume path to file system path
            if [[ -z "${mp_subvol}" ]]; then
                abs_path="${mp_norm}/${subvol}"
            elif [[ "${subvol}" == "${mp_subvol}/"* ]]; then
                abs_path="${mp_norm}/${subvol#"${mp_subvol}"/}"
            else
                # Subvolume is not under this mountpoint's subvol (e.g. sibling)
                continue
            fi
            abs_path="${abs_path//\/\///}"

            # Ignore if this path is already a known mountpoint (will be processed separately)
            [[ -n "${mps[${abs_path}]+x}" && "${abs_path}" != "${mp}" ]] && continue

            local show
            if ! show="$(btrfs subvolume show "${abs_path}" 2>/dev/null)"; then
                continue
            fi

            # Check if it's a "real" subvolume (no parent UUID) and not read-only
            if [[ "${show}" =~ "Parent UUID:"[[:space:]]+- ]] && \
               [[ ! "${show}" =~ "Flags:"[[:space:]]+readonly ]]; then
                # shellcheck disable=SC2190
                ret_val+=("${abs_path}")
            fi
        done < <(btrfs subvolume list -o "${mp}" | awk '{print $9}')
    done

    declare -p ret_val | sed -e 's/^declare -a [^=]*=//'
}

##
# Check if the given paths are BTRFS subvolumes at all.
#
# @param[in] The paths to check.
#
btrfs_wrk_paths_check()
{
    local -r wrk_paths="${1:?No paths given.}"
    local i

    for i in ${wrk_paths}; do
        local found=0
        local subvol
        # shellcheck disable=SC2154
        for subvol in "${btrfs_subvols[@]}"; do
            if [[ "${i}" == "${subvol}" ]]; then
                found=1
                break
            fi
        done

        if [ "${found}" = '0' ]; then
            log err "It appears that '${i}' is not a BTRFS file system!"
            exit "${ERR_FS_NO_BTRFS}"
        fi
    done
}

##
# Create snapshots using the paths
#
# @param[in] The paths to work with.
# @param[in] Snapshot name to create.
#
btrfs_snaps_do()
{
    local -r wrk_paths="${1:?No paths given.}"
    local -r snap_name="${2:?No snap name given.}"
    local i

    log info "Doing snapshots of ${wrk_paths}"

    for i in ${wrk_paths}; do
        local    snaps_dir
        local    snap_path
        local -a snap_opts=()

        snaps_dir="${i%/}/${DEF_SNAPS_DIR}"
        snap_path="${snaps_dir}/${snap_name}"
        # shellcheck disable=SC2206
        snap_opts=(${writeable} "${i}" "${snap_path}")

        if [ ! -d "${snaps_dir}" ]; then
            ${dry_run} mkdir -p "${snaps_dir}"
        fi

        # Creating snapshots too frequently might result in overlapping directory names,
        # which either results in error messages about read-only file systems or new
        # subdirs created in existing snapshot dirs. The latter is a problem as those
        # dirs prevent deletion of snapshots because they contain non-snap data. The
        # following is a workaround for those cases especially making tests easier.
        # Though, the same problem might occur because of changes to daylight saving
        # time, which results in the same snap names getting calculated twice. Not even
        # higher precision names containing seconds would change that.
        if [ -e "${snap_path}" ]; then
            log notice "$( ${dry_run} btrfs subvolume delete -c "${snap_path}" 2>/dev/null || :)"
        fi
        log notice "$( ${dry_run} btrfs subvolume snapshot "${snap_opts[@]}")"
    done
}

##
# Cleanup snapshots depending on how many to keep and if to cleanup at all.
#
# @param[in] The paths to work with.
# @param[in] Pattern to find snapshot names for the current prefix and label.
#
btrfs_snaps_rm_if()
{
    if [[ -z "${keep}" ]]; then
        return
    fi

    local -r wrk_paths="${1:?No paths given.}"
    local -r snap_patt="${2:?No snap pattern given.}"
    local i

    log info "Destroying all but the newest ${keep} snapshots"

    for i in ${wrk_paths}; do
        local snaps
        local snap_line
        local -a paths=()

        # We are only interested in snaps this time, which follow a hard-coded naming
        # scheme currently. We sort by generation to ensure we keep the most recent ones.
        snaps="$(btrfs subvolume list -g -o -s --sort=-gen "${i}")"
        
        while read -r snap_line; do
            [[ -z "${snap_line}" ]] && continue
            
            # Extract path (last column)
            local rel_path="${snap_line##* }"
            
            # Filter for snapshots in the .btrfs directory that match our pattern
            if [[ "${rel_path}" =~ ^(.+/)?${DEF_SNAPS_DIR}/${snap_patt}$ ]]; then
                paths+=("${i%/}/${rel_path#*/}")
            fi
        done <<< "${snaps}"

        # If we have more snapshots than we want to keep, delete the oldest ones
        if [ "${#paths[@]}" -gt "${keep}" ]; then
            local j
            # Oldest snapshots are at the end of the array because we sorted by -gen
            for ((j=keep; j<${#paths[@]}; j++)); do
                local target="${paths[$j]}"
                log notice "$( ${dry_run} btrfs subvolume delete -c "${target}")"
            done
        fi
    done
}

# Parse command line options using getopt for robust argument handling
getopt=$(getopt \
    --longoptions=debug,help,keep:,label: \
    --longoptions=dry-run,prefix:,quiet,verbose \
    --longoptions=syslog,writeable \
    --options=d,g,h,k:,l:,n,p:,q,v,w \
    -- "$@") || exit "${ERR_GETOPT_FAILED}"

eval set -- "${getopt}"
cmdline="$(argsp_cmdline "$@")"
eval "declare -A cmdline=${cmdline}"

# Map associative array back to simple variables for easier access
debug="${cmdline[debug]}"
dry_run="${cmdline[dry_run]}"
help="${cmdline[help]}"
keep="${cmdline[keep]}"
label="${cmdline[label]}"
prefix="${cmdline[prefix]}"
quiet="${cmdline[quiet]}"
use_syslog="${cmdline[use_syslog]}"
verbose="${cmdline[verbose]}"
writeable="${cmdline[writeable]}"

if [ "${help}" -eq 1 ]; then
    usage
    exit "${ERR_SUCCESS}"
fi

# Generate the snapshot name and pattern for this run
# snap_name: full directory name for the new snapshot
# snap_patt: regex pattern to identify related snapshots for rotation (matches old and new formats)
snap_name="${prefix}_${label}_$(date +%Y-%m-%dT%H:%M:%S)"
snap_patt='[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}[-T][[:digit:]]{2}:?[[:digit:]]{2}(:?[[:digit:]]{2})?'
snap_patt="${prefix}_${label}[_-]${snap_patt}"

# Discover all BTRFS mountpoints and their respective subvolume paths
btrfs_mounts="$(btrfs_mounts_calc)"
btrfs_subvols_txt="$(echo "${btrfs_mounts}" | btrfs_subvols_calc)"
eval "declare -a btrfs_subvols=${btrfs_subvols_txt}"

# Determine which paths we should operate on
if [ "${cmdline[paths]}" = '//' ]; then
    # Snapshot ALL discovered subvolumes
    wrk_paths="${btrfs_subvols[*]}"
else
    # Snapshot only the specific paths requested
    wrk_paths="${cmdline[paths]}"
fi

# Ensure all target paths are actually BTRFS subvolumes
btrfs_wrk_paths_check "${wrk_paths}"

# Perform the snapshots
btrfs_snaps_do        "${wrk_paths}" "${snap_name}"

# Rotate snapshots if a retention policy is defined
btrfs_snaps_rm_if     "${wrk_paths}" "${snap_patt}"

# vim: set expandtab:ts=4:sw=4
