#!/bin/bash

# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright notice
# and this notice are preserved.
# This file is offered as-is, without any warranty.

SUBCOMMANDS="init run stop eliminate upload take cmd status clean-cache connect"
SUBCOMMANDS+=" --help --version"

_qmm() {
    COMPREPLY=()
    curr="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    preprev="${COMP_WORDS[COMP_CWORD-2]}"
    if [[ ${COMP_CWORD} -eq 1 ]] ; then
        COMPREPLY=( $(compgen -W "${SUBCOMMANDS}" -- ${curr}) )
        return 0
    fi
    command="${COMP_WORDS[1]}"
    case "${command}" in
    init)
        if [[ ${COMP_CWORD} -eq 2 ]]; then
            COMPREPLY=( $(compgen -W "--stop" -- ${curr}) )
        fi
        return 0
        ;;
    eliminate)
        if [[ ${COMP_CWORD} -eq 2 ]]; then
            COMPREPLY=( $(compgen -W "--rm-disk" -- ${curr}) )
        fi
        return 0
        ;;
    upload)
        if [[ ${COMP_CWORD} -eq 2 ]]; then
            COMPREPLY=( $(compgen -W "--from --to" -- ${curr}) )
        elif [[ ${COMP_CWORD} -eq 4 ]]; then
            if [[ "${preprev}" == "--from" ]]; then
                COMPREPLY=( $(compgen -W "--to" -- ${curr}) )
            elif [[ "${preprev}" == "--to" ]]; then
                COMPREPLY=( $(compgen -W "--from" -- ${curr}) )
            fi
        elif [[ ${prev} == "--from" ]]; then
            COMPREPLY=( $(compgen -f -- ${curr}) )
        fi
        return 0
        ;;
    take)
        if [[ ${COMP_CWORD} -eq 2 ]]; then
            COMPREPLY=( $(compgen -W "--from --to" -- ${curr}) )
        elif [[ ${COMP_CWORD} -eq 4 ]]; then
            if [[ "${preprev}" == "--from" ]]; then
                COMPREPLY=( $(compgen -W "--to" -- ${curr}) )
            elif [[ "${preprev}" == "--to" ]]; then
                COMPREPLY=( $(compgen -W "--from" -- ${curr}) )
            fi
        elif [[ "${prev}" == "--to" ]]; then
            COMPREPLY=( $(compgen -f -- "${curr}") )
        fi
        return 0
        ;;
    cmd)
        if [[ ${COMP_CWORD} -eq 1 || "${prev}" != "-c" ]]; then
            options="-c -i --init -r --run -u --rm"
            COMPREPLY=( $(compgen -W "$options" -- ${curr}) )
        elif [[ "${prev}" == "-c" ]]; then
            if [[ -e qmmfile.json ]]; then
                named_commands="$(jq -r ".commands | keys[]" qmmfile.json)"
                COMPREPLY=( $(compgen -W "$named_commands" -- ${curr}) )
            fi
        fi
        return 0
        ;;
    esac
    return 0
}

complete -o default -F _qmm qmm
complete -o default -F _qmm ./qmm
