#!/usr/bin/bash

set -euo pipefail
shopt -s nullglob

self_name=${0##*/}

export LIB_DIR=${BTRFS_SNAPSHOTS_LIB_DIR:-/usr/lib/$self_name}
export CONFIG_DIR=${BTRFS_SNAPSHOTS_CONFIG_DIR:-/etc/$self_name}

usage="Manage timestamped collections of btrfs snapshots.

Usage:
    $self_name -h|--help
    $self_name -v|--version
    $self_name ACTION [PROFILE...]

Actions:
    list       print snapshot paths to stdout
    create     create a new snapshot in the configured location
    prune      delete snapshots that fall outside of defined limits

Arguments:
    PROFILE    profile name to perform action on (default: all)

Environment:
    ${self_name^^}_CONFIG_DIR[=${CONFIG_DIR@Q}]

See also:
    $self_name(5)
    $self_name(8)
"

if (($# > 0)); then
    if [[ $1 == -h || $1 == --help ]]; then
        printf "%s\n" "$usage"
        exit
    elif [[ $1 == -v || $1 == --version ]]; then
        printf "%s\n" "$(<"$LIB_DIR"/version)"
        exit
    fi
fi

source "$LIB_DIR"/init.bash

action_name=${1:?missing action}
shift

if [[ ! $action_name =~ ^(list|create|prune)$ ]]; then
    printf "%s: invalid action: %s\n" "$0" "$action_name" >&2
    exit 2
fi

export PROFILES_DIR=$CONFIG_DIR/profile.d
export DEFAULTS_FILE=$CONFIG_DIR/defaults.conf

profile_files=$(print_profiles "$@") || exit

while IFS= read -r profile_file; do
    if ! load_profile "$profile_file"; then
        printf "%s: unable to load profile: %q\n" "$0" "$profile_file" >&2
        exit 2
    fi
    if ! do_"$action_name"; then
        printf "%s: unable to perform action '%s' for profile: %q\n" "$0" "$action_name" "$profile_file" >&2
        exit 1
    fi
done <<<"$profile_files"
