#!/usr/bin/bash

set -euo pipefail
shopt -s nullglob

export 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 [OPTIONS] ACTION [PROFILE...]

Options:
    -h, --help       show this help message and exit
    -v, --version    show the program's version number and exit

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)
"

while (($# > 0)); do
    arg=$1
    [[ $arg == -* ]] || break
    shift

    if [[ $arg == -- ]]; then
        break
    elif [[ $arg == -h || $arg == --help ]]; then
        printf "%s\n" "$usage"
        exit
    elif [[ $arg == -v || $arg == --version ]]; then
        printf "%s\n" "$(<"$LIB_DIR"/version)"
        exit
    else
        printf "%s: invalid option: %s\n" "$SELF_NAME" "$arg" >&2
        exit 64
    fi
done

action_name=${1:?missing action}
shift

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

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

source "$LIB_DIR"/init.bash

profile_files=$(print_profiles "$@")

if [[ -z $profile_files ]]; then
    printf "%s: no profiles configured\n" "$SELF_NAME" >&2
    exit 66
fi

while IFS= read -r profile_file; do
    load_profile "$profile_file"
    do_"$action_name"
done <<<"$profile_files"
