#!/bin/bash


_autocommandrun() {
    command="$1"
    key="$2"
    value="$3"

    # only passed through if command is backup or restore.
    backup_file="$4"
    temp_path="$5"
    
    case "$key" in
        volume)
            echo "Volume: $value"
            ;;
        path)
            echo "Path: $value"
            ;;
        file)
            echo "File: $value"
            ;;
        *)
            _die "Unknown key $key passed to auto${command}. We only support volume, path and file."
            ;;
    esac
}

_autocommandparse() {
    # first argument is the command
    # if the command is backup or restore, then the last two arguments are the backup file and the temporary path
    # all other arguments are of form:
    # key=value
    # where key can be one of volume, path or file.
    # value is the path or volume name.

    # we iterate over the key=value arguments, and for each we call:
    #    autorun <command> <key> <value> <backup_file> <temp_path>

    local command="$1"
    shift

    # Extract the backup file and temp path (last two arguments)
    local args=("$@")
    local arg_count=${#args[@]}
    local backup_file="${args[$arg_count-2]}"
    local temp_path="${args[$arg_count-1]}"
    
    # Process all key=value pairs
    for ((i=0; i<$arg_count-2; i++)); do
        local pair="${args[$i]}"
        
        # Skip if not in key=value format
        if [[ "$pair" != *"="* ]]; then
            continue
        fi
        
        local key="${pair%%=*}"
        local value="${pair#*=}"
        
        # Key must be one of volume, path or file
        _autocommandrun "$command" "$key" "$value" "$backup_file" "$temp_path"
    done
}


autocreate() {
    _autocommandparse create "$@" "-" "-"
}


autonuke() {
    _autocommandparse nuke "$@" "-" "-"
}


autobackup() {
    _autocommandparse backup "$@"
}


autorestore() {
    _autocommandparse restore "$@"
}


