#/usr/bin/env bash

COMMANDS="apply list manage print-state reinstall render render-all report restart show status version"

_hostctl_units()
{
    COMPREPLY=($(compgen -W "$(hostctl list -o 1 2>/dev/null)" "${COMP_WORDS[2]}" ))
}

_hostctl_completions()
{
    if [ "${#COMP_WORDS[@]}" = "2" ]; then
        COMPREPLY=($(compgen -W "${COMMANDS}" "${COMP_WORDS[1]}"))
        return
    fi
    case "${COMP_WORDS[1]}" in
    reinstall|restart|show|status|manage)
        _hostctl_units
        ;;
    manage)
        # FLAGS="$(hostctl "${COMP_WORDS[1]}" -h | grep -- ' --' | sed -E 's/.* --([a-zA-Z-]+) .*/\1/'|awk '{print "--" $1}')"
        # "static" version of above FLAGS
        read -r -d '' FLAGS <<-EOF
            --ctype
            --help
            --include
            --logfile
            --mem-profile
            --no-orly
            --noop
            --orly-url
            --report-addr
            --stdin
            --target-units
            --units
            --verbose
EOF
        if [[ ${COMP_WORDS[-1]} == --*  ]]; then
            WORDS="$(echo "$FLAGS" | grep -- "${COMP_WORDS[-1]}")"
            COMPREPLY=($(compgen -W "${WORDS}"))
        else
            COMPREPLY=($(compgen -W "${FLAGS}" ))
	fi
        ;;
    report)
        # FLAGS="$(hostctl "${COMP_WORDS[1]}" -h | grep -- ' --' | sed -E 's/.* --([a-zA-Z-]+) .*/\1/'|awk '{print "--" $1}')"
        # "static" version of above FLAGS
        read -r -d '' FLAGS <<-EOF
            --ctype
            --help
            --include
            --logfile
            --report-addr
            --verbose
EOF
        if [[ ${COMP_WORDS[-1]} == --*  ]]; then
            WORDS="$(echo "$FLAGS" | grep -- "${COMP_WORDS[-1]}")"
            COMPREPLY=($(compgen -W "${WORDS}"))
        else
            COMPREPLY=($(compgen -W "${FLAGS}" ))
	fi
        ;;
    esac
}

complete -F _hostctl_completions hostctl
