_btrfs_snapshots() {
    # local cmd_name=$1
    local cur=$2
    # local prev=$3

    local flags=(-h --help -v --version)
    local actions=(list create prune)

    case $cur in
    -*)
        if ((COMP_CWORD == 1)); then
            readarray -t COMPREPLY < <(compgen -W "${flags[*]}" -- "$cur")
        fi
        ;;
    *)
        if ((COMP_CWORD == 1)); then
            readarray -t COMPREPLY < <(compgen -W "${actions[*]}" -- "$cur")
        elif ((COMP_CWORD >= 2)) && [[ ${COMP_WORDS[1]} != -* ]]; then
            local config_dir=${BTRFS_SNAPSHOTS_CONFIG_DIR:-/etc/btrfs-snapshots}

            local profile
            local -A used_profiles=()

            for profile in "${COMP_WORDS[@]:2}"; do
                if [[ -n $profile ]]; then
                    used_profiles[$profile]=1
                fi
            done

            local profiles=()

            for profile in "$config_dir"/profile.d/*.conf; do
                if [[ -f $profile ]]; then
                    profile=${profile##*/}
                    profile=${profile%.conf}
                    if [[ ! -v used_profiles[$profile] ]]; then
                        profiles+=("$profile")
                    fi
                fi
            done

            readarray -t COMPREPLY < <(compgen -W "${profiles[*]}" -- "$cur")
        fi
        ;;
    esac
}

complete -F _btrfs_snapshots btrfs-snapshots
