# SPDX-License-Identifier: LGPL-2.1-or-later
# shellcheck shell=bash

_mkosi_compgen_files() {
    compgen -f -- "$1"
}

_mkosi_compgen_dirs() {
    compgen -d -- "$1"
}

_mkosi_completion() {
    local -a _mkosi_options
    local -A _mkosi_choices _mkosi_compgen _mkosi_verbs
    local -i curword_idx verb_seen

    _mkosi_options=(-f -C -B -w -R -I -d -r -m -t -o -O -p -a -i -E -T --force --directory --debug --debug-shell --debug-workspace --debug-sandbox --no-pager --genkey-valid-days --genkey-common-name --auto-bump --doc-format --json --wipe-build-dir --rerun-build-scripts --include --profile --dependency --minimum-version --configure-script --pass-environment --distribution --release --architecture --mirror --snapshot --local-mirror --repository-key-check --repository-key-fetch --repositories --format --manifest-format --output --output-extension --compress-output --compress-level --output-directory --output-mode --image-version --image-id --split-artifacts --repart-directory --sector-size --overlay --seed --clean-script --package --build-package --volatile-package --package-directory --volatile-package-directory --with-recommends --with-docs --base-tree --skeleton-tree --extra-tree --remove-package --remove-files --clean-package-metadata --source-date-epoch --sync-script --prepare-script --build-script --postinst-script --finalize-script --postoutput-script --bootable --bootloader --bios-bootloader --shim-bootloader --unified-kernel-images --unified-kernel-image-format --uki-profile --initrd --microcode-host --initrd-profile --initrd-package --initrd-volatile-package --devicetrees --splash --kernel-command-line --kernel-modules-include --kernel-modules-exclude --kernel-modules --kernel-modules-include-host --kernel-modules-initrd --kernel-modules-initrd-include --kernel-modules-initrd-exclude --kernel-initrd-modules --kernel-modules-initrd-include-host --firmware-include --firmware-exclude --firmware-files --locale --locale-messages --keymap --timezone --hostname --root-password --root-shell --machine-id --autologin --make-initrd --ssh --selinux-relabel --secure-boot --secure-boot-auto-enroll --secure-boot-key --secure-boot-key-source --secure-boot-certificate --secure-boot-certificate-source --secure-boot-sign-tool --verity --verity-key --verity-key-source --verity-certificate --verity-certificate-source --sign-expected-pcr --sign-expected-pcr-key --sign-expected-pcr-key-source --sign-expected-pcr-certificate --sign-expected-pcr-certificate-source --passphrase --checksum --sign --key --openpgp-tool --tools-tree --tools-tree-distribution --tools-tree-release --tools-tree-profile --tools-tree-mirror --tools-tree-repository --tools-tree-sandbox-tree --tools-tree-package --tools-tree-package-directory --tools-tree-certificates --extra-search-path --incremental --cache-only --sandbox-tree --workspace-directory --cache-directory --cache-key --package-cache-directory --build-directory --build-key --use-subvolumes --repart-offline --history --build-sources --build-sources-ephemeral --environment --env-file --with-tests --with-network --proxy-url --proxy-exclude --proxy-peer-certificate --proxy-client-certificate --proxy-client-key --settings --ephemeral --credential --kernel-command-line-extra --runtime-tree --runtime-size --runtime-network --runtime-build-sources --bind-user --unit-property --ssh-key --ssh-certificate --vmm --machine --forward-journal --sysupdate-directory --console --cpus --ram --maxmem --kvm --cxl --vsock --vsock-cid --tpm --removable --firmware --firmware-variables --linux --drive --qemu-args --register --storage-target-mode)

    _mkosi_choices=([-d]='fedora debian kali ubuntu postmarketos arch opensuse mageia centos rhel rhel-ubi openmandriva rocky alma azure custom ' [-t]='confext cpio directory disk esp none portable sysext tar uki oci addon ' [-i]='yes no strict' [--doc-format]='auto markdown man pandoc system' [--distribution]='fedora debian kali ubuntu postmarketos arch opensuse mageia centos rhel rhel-ubi openmandriva rocky alma azure custom ' [--architecture]='alpha arc arm arm64 ia64 loongarch64 mips-le mips64-le parisc ppc ppc64 ppc64-le riscv32 riscv64 s390 s390x tilegx x86 x86-64 ' [--format]='confext cpio directory disk esp none portable sysext tar uki oci addon ' [--bootloader]='none uki systemd-boot grub uki-signed systemd-boot-signed grub-signed ' [--bios-bootloader]='none grub ' [--shim-bootloader]='none signed unsigned ' [--initrd-profile]='lvm network nfs pkcs11 plymouth raid' [--ssh]='always auto runtime never ' [--secure-boot-sign-tool]='auto sbsign systemd-sbsign ' [--verity]='disabled hash signed defer auto' [--tools-tree-distribution]='fedora debian kali ubuntu postmarketos arch opensuse mageia centos rhel rhel-ubi openmandriva rocky alma azure custom ' [--tools-tree-profile]='devel misc package-manager runtime' [--incremental]='yes no strict' [--cache-only]='always auto none metadata never ' [--build-sources-ephemeral]='yes no buildcache' [--runtime-network]='interface user none ' [--vmm]='qemu vmspawn ' [--firmware]='auto linux linux-noinitrd uefi uefi-secure-boot bios ')

    _mkosi_compgen=([-C]=_mkosi_compgen_dirs [--directory]=_mkosi_compgen_dirs)

    _mkosi_verbs=([build]=build [clean]=clean [summary]=summary [cat-config]=cat-config [shell]=shell [boot]=boot [vm]=vm [qemu]=qemu [ssh]=ssh [serve]=serve [bump]=bump [help]=help [genkey]=genkey [documentation]=documentation [journalctl]=journalctl [coredumpctl]=coredumpctl [burn]=burn [dependencies]=dependencies [completion]=completion [sysupdate]=sysupdate [box]=box [sandbox]=sandbox [init]=init [latest-snapshot]=latest-snapshot)

    # completing_program="$1"
    local completing_word="$2"
    local completing_word_preceding="$3"

    if [[ "$completing_word" =~ ^- ]]  # completing an option
    then
        readarray -t COMPREPLY < <(compgen -W "${_mkosi_options[*]}" -- "${completing_word}")
        return
    elif [[ "$completing_word_preceding" =~ ^- ]]  # the previous word was an option
    then
        current_option="${completing_word_preceding}"
        current_option_choices="${_mkosi_choices[${current_option}]}"
        current_option_compgen="${_mkosi_compgen[${current_option}]}"

        # compgen options if we have them
        if [[ -n "${current_option_compgen}" ]]
        then
            readarray -t COMPREPLY < <("${current_option_compgen}" "${completing_word}")
            return
        fi

        # add choices if the current option has them
        readarray -t COMPREPLY -O "${#COMPREPLY[@]}" \
                  < <(compgen -W "${current_option_choices}" -- "${completing_word}")

        # if this (maybe) takes arguments, we'll just fall back to files
        readarray -t COMPREPLY -O "${#COMPREPLY[@]}" \
                    < <(_mkosi_compgen_files "${completing_word}")
    fi

    # the preceding word wasn't an option or one that doesn't take arguments,
    # let's get creative and check the whole argument list so far
    while ((curword_idx < COMP_CWORD))
    do
        # check if we've seen a verb already, then we just try files
        if [[ -n "${_mkosi_verbs[${COMP_WORDS[${curword_idx}]}]}" ]]
        then
            verb_seen=$curword_idx
            break
        fi
        curword_idx=$((curword_idx + 1))
    done
    if ((verb_seen))
    then
        readarray -t COMPREPLY < <(_mkosi_compgen_files "${completing_word}")
    else
        readarray -t COMPREPLY < <(compgen -W "${_mkosi_verbs[*]}" -- "${completing_word}")
    fi
}

complete -o filenames -F _mkosi_completion mkosi
complete -o filenames -F _mkosi_completion python -m mkosi

